Вопрос

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!!

Это было полезно?

Решение

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");

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top