简体   繁体   中英

How to execute another java program via shell command from java program

I am supposed to make an IDE for my project. Here I have to execute a java program(suppose Hello world ) via a Shell command from a specific java program. I know how to execute a shell command via java program (using Runtime.getRuntime()),but how do I invoke run a java program using this shell command.

Start with ProcessBuilder , it will allow you to separate each command argument as a separate parameter, removing the need to "quote" arguments that have spaces (like paths), it will allow you to specify the starting location of the command (working directory) and the redirection support makes it easier to extract information from the output of the command (although you might like to keep it separate)...

 List<String> cmds = new ArrayList<String>(5); // You can use arrays as well
 cmds.add("java");
 cmds.add("-jar");
 cmds.add("filename.jar");
 ProcessBuilder pb = new ProcessBuilder(cmds);
 pb.redirectErrorStream(true);
 pb.directory(new File("...")); // Working directory...
 Process p = pb.start();
 // Normal processing of the Process...

You can even specify the environment variables passed to the process...

Take a look at the Java Docs for more details

This will work.
Setup the commands and then create runtime and execute command there.

String command[] = new String[4];
command[0] = "cmd";
command[1] = "/k start cmd /k";
command[2] = "java";
command[3] = path;

Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));  //This will allow you to supply with input
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));  //This will provide you access to the errors.
pw = new PrintWriter(p.getOutputStream());      
pw.println("next commands");

The PrintWriter object will allow you to execute more commands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM