Runtime.getRuntime (). Exec () executing Java class

I am executing a Java class from within my application.

proc = Runtime.getRuntime().exec("java Test"); 

How can I find out if Test succeeds or not (i.e. no exceptions)?


Output / Error Redirection:

 proc = Runtime.getRuntime().exec(new String[] { "java", mclass, ">NUL 2>test.txt" }); 

From cmd :

 java Main >NUL 2>test.txt 
+4
source share
6 answers
 process.waitFor(); int exitCode = process.exitValue(); if(exitCode == 0) { // success } else { // failed } 

This works if Test designed correctly and returns the appropriate exit codes (typically> 0 if something went wrong).

If you want to receive the Test output / error message to determine what is wrong, you should get proc.getInputStream() (this returns the output stream of the child process), proc.getErrorStream() and read from the input streams in split streams.

Note that the child process will be blocked if it writes to the error / output stream and there are no readers. Thus, the read / output streams of a process are useful anyway.

Another option to avoid blocking for children is to redirect their error / output to a file and / or to /dev/null ("NUL" for windows):

 Runtime.exec("java Test >/dev/null 2>&1"); Runtime.exec("java Test >/dev/null 2>erroroutput"); 
+7
source

Redirection is performed by the shell processor, not Runtime.exec() (at least not on Windows).
You need to execute cmd.exe command:

 String command = "cmd /c java -classpath D:\\dev\\temp\\ Main >NUL 2>test.txt"; proc = Runtime.getRuntime().exec(command); 
+2
source

See process class

You can call proc.waitFor() to return an integer value. But you must make sure that all the output of the program is processed correctly (for example, use the proc.getInputStream() method).

+1
source

Have you tried proc.exitValue() ?

+1
source

Errr ... what? Do it like this:

 int response = (int)(getClass().getClassLoader().findClass("Test"). getMethod("someStaticMethod", new String[]{}). invoke(null, new Object[]{})); 

This calls the static method "int someStaticMethod ()" of the class "Test", which is dynamically loaded.

0
source

You can use the java class for ProcessBuilder to execute these files.

0
source

All Articles