Organizational Research By

Surprising Reserch Topic

running command line in java


running command line in java  using -'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.'

asked Sep 16, 2015 by patelnikul321
edited Sep 16, 2015 by rajesh
0 votes
5 views



Related Hot Questions

5 Answers

0 votes
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

answered Sep 16, 2015 by akhilesh
0 votes

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.

answered Sep 16, 2015 by abhi
0 votes
import java.io.*;

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

Consider the following if you run into any further problems, but I'm guessing that the above will work for you:

Problems with Runtime.exec()

answered Sep 16, 2015 by patilkiran.101
0 votes

Have you tried the exec command within the Runtime class?

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug")

Runtime - Java Documentation

answered Sep 16, 2015 by rajesh
0 votes

To avoid the called process to be blocked if it outputs a lot of data on the standard output and/or error, you have to use the solution provided by Craigo. Note also that ProcessBuilder is better than Runtime.getRuntime().exec(). This is for a couple of reasons: it tokenizes better the arguments, and it also takes care of the error standard output (check also here).

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

// Watch the process
watch(process);

I use a new function "watch" to gather this data in a new thread. This thread will finish in the calling process when the called process ends.

private static void watch(final Process process) {
    new Thread(new Runnable() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null; 
            try {
                while ((line = input.readLine()) != null) {}
                } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
answered Sep 16, 2015 by vickeykumar66

...