为了账号安全,请及时绑定邮箱和手机立即绑定

Java runtime.getruntime()从执行命令行程序获得输出

Java runtime.getruntime()从执行命令行程序获得输出

慕村9548890 2019-06-16 14:26:40
Java runtime.getruntime()从执行命令行程序获得输出我正在使用运行时从我的Java程序运行命令提示符命令。但是,我不知道如何获得命令返回的输出。这是我的代码:Runtime rt = Runtime.getRuntime();String[] commands = {"system.exe" , "-send" , argument};Process proc = rt.exec(commands);我试着做System.out.print(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);但是,我没有得到任何作为我的输出,但当我运行该命令自己,它工作良好。
查看完整描述

4 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

这就是我们要走的路:

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是个很好的选择



查看完整回答
反对 回复 2019-06-16
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

一个更快的方法是:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";}

这基本上是一个浓缩的版本:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;}

我知道这个问题已经过时了,但我在贴出这个答案是因为我认为这可能会更快一些。


查看完整回答
反对 回复 2019-06-16
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

除了使用ProcessBuilder如森提建议的那样,一定要阅读并执行的建议当Runtime.exec()不会.


查看完整回答
反对 回复 2019-06-16
  • 4 回答
  • 0 关注
  • 10239 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信