0

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)?

1
  • 1
    You can call java compiler without necessarily relying on running an external process, by using a javax.tools.ToolProvider.getSystemJavaCompiler(). Commented Nov 24, 2017 at 15:59

1 Answer 1

1

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.c‌​lass.

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();.

Sign up to request clarification or add additional context in comments.

1 Comment

I really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.