在Java中运行命令行

Ata*_*man 118 java command-line runtime.exec

有没有办法在Java应用程序中运行此命令行?

java -jar map.jar time.rel test.txt debug
Run Code Online (Sandbox Code Playgroud)

我可以用命令运行它但我无法在Java中执行它.

kol*_*kol 179

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");
Run Code Online (Sandbox Code Playgroud)

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

  • 使用`pr.getInputStream()`.这是一个详细的例子:http://www.linglom.com/2007/06/06/how-to-run-command-line-or-execute-external-application-from-java/ (7认同)
  • 检查进程返回的内容非常有用.你可以使用pr.waitFor()获得它.所以它看起来像这样:`int retVal = pr.waitFor()`.所以,如果它不是0,你可以中止/清理. (6认同)
  • 没有什么比"Runtime rt = Runtime.getRuntime();"更多的java (3认同)

Cra*_*igo 48

您还可以像这样观看输出:

final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

new Thread(new Runnable() {
    public void run() {
     BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line = null; 

     try {
        while ((line = input.readLine()) != null)
            System.out.println(line);
     } catch (IOException e) {
            e.printStackTrace();
     }
    }
}).start();

p.waitFor();
Run Code Online (Sandbox Code Playgroud)

不要忘记,如果您在Windows中运行,则需要在命令前放置"cmd/c".

  • 您还可以使用p.getErrorStream来理解命令被破坏的原因! (5认同)
  • 实际上,我认为你只需要"cmd/c",如果你想运行一个windows命令,比如"copy".为混乱道歉. (2认同)

mou*_*rix 18

为了避免在标准输出和/或错误输出大量数据时阻止被调用进程,您必须使用Craigo提供的解决方案.另请注意,ProcessBuilder优于Runtime.getRuntime().exec().这有几个原因:它更好地标记了参数,并且还处理错误标准输出(也请在此处查看).

ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();

// Watch the process
watch(process);
Run Code Online (Sandbox Code Playgroud)

我使用新功能"watch"在新线程中收集这些数据.当被调用的进程结束时,该线程将在调用进程中完成.

private static void watch(final Process process) {
    new Thread() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null; 
            try {
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}
Run Code Online (Sandbox Code Playgroud)


Igo*_*pov 8

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Run Code Online (Sandbox Code Playgroud)


Sha*_*aun 8

import java.io.*;

Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Run Code Online (Sandbox Code Playgroud)

如果您遇到任何进一步的问题,请考虑以下问题,但我猜测上述内容对您有用:

Runtime.exec()的问题