问题描述
我正在使用运行时从我的Java程序运行命令提示符命令。但是我不知道如何获得命令返回的输出。
I'm using the runtime to run command prompt commands from my Java program. However I'm not aware of how I can get the output the command returns.
这是我的代码:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe" , "-send" , argument};
Process proc = rt.exec(commands);
我试过做 System.out.print(proc);
但是没有返回任何东西。该命令的执行应返回由分号分隔的两个数字,我怎样才能在变量中打印出来?
I tried doing System.out.print(proc);
but that did not return anything. The execution of that command should return two numbers separated by a semicolon, how could I get this in a variable to print out?
这是我现在使用的代码:
Here is the code I'm using now:
String[] commands = {"system.exe","-get t"};
Process proc = rt.exec(commands);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
但我没有得到任何东西作为我的输出但是当我自己运行该命令时它工作正常。
But I'm not getting anything as my output but when I run that command myself it works fine.
推荐答案
以下是要走的路:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe","-get t"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
更好地阅读Javadoc了解更多详情。 ProcessBuilder
将是不错的选择
Better read the Javadoc for more details here. ProcessBuilder
would be good choice to use
这篇关于java runtime.getruntime()从执行命令行程序获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!