Running Command Line in Java [duplicate]

2018-12-31 14:43发布

This question already has an answer here:

Is there a way to run this command line within a Java application?

java -jar map.jar time.rel test.txt debug

I can run it with command but I couldn't do it within Java.

8条回答
不流泪的眼
2楼-- · 2018-12-31 15:40

You can also watch the output like this:

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();

And don't forget, if you are running in Windows, you need to put "cmd /c " in front of your command.

查看更多
旧时光的记忆
3楼-- · 2018-12-31 15:49
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

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

查看更多
登录 后发表回答