在程序中调用dos命令,并返回结果:
String command = "cmd.exe /c ver";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));将ver改成dir后就没有返回结果了,只能返回一些文本信息吗?
String command = "cmd.exe /c ver";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));将ver改成dir后就没有返回结果了,只能返回一些文本信息吗?
修改为String command = "cmd /c ver";参考:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;public class ExecCommand
{ public static String exec(String execStr) throws IOException
{
Runtime runtime = Runtime.getRuntime();
String outInfo = "";
String[] args = new String[]
{ "cmd", "/c", execStr };
Process proc = runtime.exec(args); //
InputStream in = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null)
{
outInfo = outInfo + line + "\n";
System.out.println(outInfo);
}
try
{
if (proc.waitFor() != 0)
{
System.err.println("exit value = " + proc.exitValue());
}
} catch (InterruptedException e)
{
System.err.print(e);
e.printStackTrace();
}
return outInfo;
}
public static void main(String[] args)
{
try
{
ExecCommand.exec("dir");
} catch (IOException e)
{
e.printStackTrace();
}
}
}