Runtime.getRuntime().exec(), executing Java class

て烟熏妆下的殇ゞ 提交于 2019-12-05 16:41:29
khachik
process.waitFor();
int exitCode = process.exitValue();
if(exitCode == 0) { // success }
else { // failed }

This works, if the Test is designed properly and returns appropriate exit codes (generally, >0 if something went wrong).

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

Note that the child process will get blocked if it writes to error/output stream and there are no readers. So reading error/output streams of the process is useful in any cases.

Another option to avoid child blocking is to redirect its 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");

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

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

See the Process class

You can call proc.waitFor() to return an integer value. But you have to make sure that all output of the program is handled correctly (e.g. use the proc.getInputStream() method).

Have you tried proc.exitValue() ?

Errr... what? Do it this way:

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

This invokes the static method "int someStaticMethod()" of the class "Test" which gets loaded dynamically.

You may use ProcessBuilder class of java to execute these files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!