I'm trying to run other java file using ProcessBuilder
class.
I would like to get input of entire path of java file + file name + .java and compile it.
Example, input: C:\Windows\test.java
And then, I store input into String
variable FILE_LOCATION
and call processbuilder
to compile input .java file.
Here is my code:
static String JAVA_FILE_LOCATION;
static String command[] = {"javac", JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
process = new ProcessBuilder(new String[]{"java","-cp",A,B}).start();
But I don't know how to set the parameters.
process = new ProcessBuilder(new String[]{
"java","-cp",A,B}).start();
How should I set that parameter (A, B)
?
To answer your exact question, let's say, for instance, your class is in package com.yourcompany.yourproduct
and your class file is in /dir/to/your/classes/com/yourcompany/yourproduct/Yourclass.class.
Then A = "/dir/to/your/classes"
and B = "com.yourcompany.yourproduct.Yourclass"
.
However, there's a few things to be aware of. Looking at your code:
static String JAVA_FILE_LOCATION;
static String command[] = {"javac", JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);
No. You need to CD to the directory and then run javac
. The easiest way to do that is by calling processBuilder.directory(new File("/dir/to/your/classes"))
. Then you need to give javac
a relative path to your source file ("com/yourcompany/yourproduct/Yourclass.java"
).
Process process = processBuilder.start();
process = new ProcessBuilder(new String[]{"java","-cp",A,B}).start();
Wait until the first process has finished compiling before you try to run it! Between the two lines above, insert process.waitFor();
. You might also want to check for any errors and only run the second process if the first has succeeded.
By the way, there's no need for all that long-hand creation of string arrays. Just use varargs: process = new ProcessBuilder("java", "-cp", A, B).start();
.