ProcessBuilder not executing Java class file properly

て烟熏妆下的殇ゞ 提交于 2019-12-10 19:28:22

问题


In a java file I am calling command line statement to execute another java file. This is what I am doing:

List<String> paramsExecute = new ArrayList<String>();
paramsExecute.add("java");
paramsExecute.add("-cp");
paramsExecute.add("input\programs\User_K Program1");
paramsExecute.add("1 2 3");

ProcessBuilder builderExecute = new ProcessBuilder(paramsExecute);

builderExecute.redirectOutput(new File(a.txt));
builderExecute.redirectError(new File(b.txt));

Execution of one of the Java files is producing b.txt as:

Error: Could not find or load main class 1 2 3

Another java file is producing b.txt as:

Usage: java [-options] class [args...] ...

But, when I am running these statements directly from the command line, it is executing correctly. The folder input\programs\ is in the same path as the src folder. The src folder contains the Java file containing the ProcessBuilder program. I have verified that the .class file is getting created correctly and in the right folder. I am running the program in windows.

Any help appreciated!!


回答1:


This paramsExecute.add("input\programs\User_K Program1"); is been treated as a single command/parameter, saying that the class path should be equal to input\programs\User_K Program1

I think you want to use something more like...

paramsExecute.add("input\programs\User_K");
paramsExecute.add("Program1");



回答2:


You should specify the classpath after '-cp' like

List<String> params = new ArrayList<String>();
params.add("java"); /* name of program to run, java */
params.add("-cp");  /* -cp */
params.add(System.getProperty("java.class.path")); /* class path information */
params.add("pkg.to.yourclass.ClassToRun"); /* full quailified class name */
params.add("1"); params.add("2"); params.add("3"); /* this is parameter to main */

"input\programs\User_K Program1" in your code is treated as a classpath information, not class to run because it follows '-cp', and "1 2 3" as a class name, not arguments passed to the main method.

It is not easy to retrieve classpath from the scatch.

If you want to create a process using an class located in the sample src folder, It is good to use System.getProperty("java.class.path"); to inherite classpath, or You should type the path info manually.



来源:https://stackoverflow.com/questions/22137387/processbuilder-not-executing-java-class-file-properly

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