Java runtime class

How to execute a java program using Runtime.getRuntime (). exec (). For example, we will have the path to the java file as c: /java/abc.java. Please help me with the code.

+3
source share
6 answers

Assuming abc.java contains the main method you want to execute:

Runtime.getRuntime().exec("javac c:\java\abc.java -dc:\java\") Runtime.getRuntime().exec("java c:\java\abc") 
+2
source

Do not forget that:

  • you may need to read stdout / stderr java programs
  • you may need to set / update the environment variable and PATH before executing the java command

    CreateProcess: c: \ j2sdk1.4.0 \ bin \ helloworld error = 2

means Win32 CreateProcess returns 2 as an error code when it cannot find the specified command; more specifically, when a command does not reference an executable file in a search path.

Runtime.getRuntime().exec() look at this SO question for more complete Runtime.getRuntime().exec() code, as well as this snippet .

This code creates a shell (as in Runtime.getRuntime().exec("cmd /K") ), in which you write to sdtin any command that you want to execute.

An interest in this approach is to reuse the shell process to take advantage of the previous command: you execute " cd ", then execute " dir ", the last command displays the contents of the directory using the cd .

The same would be true for PATH options, just before using javac or java .

+2
source

Instead, you should use ProcessBuilder . Main use:

 Process process = new ProcessBuilder(command).start(); 

You will find more code at the link above. Also see this question .

+2
source

You want the Java program to run another Java program. This SO stream may be useful in this case.

+1
source
 String path1 = "f://" + File.separator+username+File.separator+progName; Runtime runtime = Runtime.getRuntime(); String command = "javac -classpath " + path + " " + path1; System.out.println(command); Process process = runtime.exec(command); InputStream error = process.getErrorStream(); 
+1
source

Check out the great resource that used to be called javaalmanac.

http://www.exampledepot.com/egs/java.lang/Exec.html

 try { // Execute a command with an argument that contains a space String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"}; commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"}; Process child = Runtime.getRuntime().exec(commands); } catch (IOException e) { } 
0
source

Source: https://habr.com/ru/post/904634/


All Articles