Running Command Line in Java

JavaCommand Lineruntime.exec

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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 a windows command, you need to put cmd /c in front of your command.

EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:

String[] command = new String[] {
        "choice",
        "/C",
        "YN",
        "/M",
        "\"Press Y if you're cool\""
};
String inputLine = "Y";

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

writer.write(inputLine);
writer.newLine();
writer.close();

String line;

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:

Press Y if you're cool [Y,N]?Y

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

what about

public class CmdExec {

public static Scanner s = null;


public static void main(String[] args) throws InterruptedException, IOException {
	s = new Scanner(System.in);
	System.out.print("$ ");
	String cmd = s.nextLine();
	final Process p = Runtime.getRuntime().exec(cmd);

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

 }

Solution 7 - Java

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

Solution 8 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtamanView Question on Stackoverflow
Solution 1 - JavakolView Answer on Stackoverflow
Solution 2 - JavaCraigoView Answer on Stackoverflow
Solution 3 - JavamountrixView Answer on Stackoverflow
Solution 4 - JavaIgor PopovView Answer on Stackoverflow
Solution 5 - JavaShaunView Answer on Stackoverflow
Solution 6 - JavaDenisView Answer on Stackoverflow
Solution 7 - JavaFunky coderView Answer on Stackoverflow
Solution 8 - JavarybosomeView Answer on Stackoverflow