当前位置: 技术问答>java相关
请问JAVA如何执行(调用)操作系统命令,如dir,然后把执行结果存入变量或文件,谢谢!
来源: 互联网 发布时间:2015-10-16
本文导语: 请问JAVA如何执行(调用)操作系统命令,如dir,然后把执行结果存入变量或文件,谢谢! | import java.io.*; class PT { public static void main(String[] args) throws IOException { String filename="out.txt"; ...
请问JAVA如何执行(调用)操作系统命令,如dir,然后把执行结果存入变量或文件,谢谢!
|
import java.io.*;
class PT
{
public static void main(String[] args) throws IOException
{
String filename="out.txt";
if(args.length>0){
filename=args[0];
}
String command="cmd /C dir";
Runtime r=Runtime.getRuntime();
Process p=r.exec(command);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
PrintStream ps=new PrintStream(new FileOutputStream(filename));
String inline;
while(null!=(inline=br.readLine())){
ps.println(inline);
}
System.out.println("a command result has been readed to a file "+filename);
}
}
class PT
{
public static void main(String[] args) throws IOException
{
String filename="out.txt";
if(args.length>0){
filename=args[0];
}
String command="cmd /C dir";
Runtime r=Runtime.getRuntime();
Process p=r.exec(command);
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
PrintStream ps=new PrintStream(new FileOutputStream(filename));
String inline;
while(null!=(inline=br.readLine())){
ps.println(inline);
}
System.out.println("a command result has been readed to a file "+filename);
}
}