Java Runtime.getRuntime():从执行命令行程序获取输出
我正在使用运行时从我的 Java 程序运行命令提示符命令。但是,我不知道如何获得命令返回的输出。
这是我的代码:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send" , argument};
Process proc = rt.exec(commands);
我试过做System.out.println(proc);
,但没有返回任何东西。该命令的执行应返回由分号分隔的两个数字。我怎么能把它放在一个变量中打印出来?
这是我现在使用的代码:
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);
但是我没有得到任何输出,但是当我自己运行该命令时,它可以正常工作。
-
这是要走的路:
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
将是一个不错的选择。
-
Java Runtime.getRuntime():从执行命令行程序获取输出
2021-02-02 关注 0 浏览239 1答案
-
从python中执行命令行程序
2022-04-11 关注 0 浏览21 1答案
-
从python内部执行命令行程序
2021-01-29 关注 0 浏览104 1答案
-
Java执行命令行程序'find'返回错误
2021-01-29 关注 0 浏览102 1答案
-
怎么使用 SpringBoot 去执行命令行程序?
2020-07-11 关注 0 浏览625 1答案
-
使用Runtime.getRuntime()。exec()执行Java文件
2021-01-29 关注 0 浏览108 1答案
-
尝试使用Runtime.getRuntime()。exec()执行Java jar
2021-01-30 关注 0 浏览97 1答案
-
java Runtime.getRunTime()。exec和通配符?
2021-01-31 关注 0 浏览88 1答案
-
如何在Java中执行命令行.exe文件
2021-01-30 关注 0 浏览155 1答案
-
使用Runtime.getRuntime()。exec从定义的目录中执行文件
2021-01-30 关注 0 浏览110 1答案