且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Runtime.getRuntime():从执行命令行程序中获取输出

更新时间:2023-11-11 22:00:16

方法如下:

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 将是一个不错的选择.

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.