How to run a Java program using ProcessBuilder ins

2019-07-20 16:24发布

问题:

Here is my code.

public class Test {
    public static void main(String[] args) {
        String directory = System.getProperty("user.home") + File.separator + "cache";
        System.out.println(directory); // "/Users/byron1st/cache"
        try{
            ProcessBuilder builder = new ProcessBuilder("java",
                    "-cp", directory,
                    "-Xbootclasspath/p:", directory,
                    "framework.PFSystemMain");
            builder.redirectErrorStream(true);
            builder.redirectOutput(new File(System.getProperty("user.home") + "/output.txt"));
            builder.start();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

This program builds a process to run a java program with -cp and -Xbootclasspath commands. Classes of the target program are in /Users/byron1st/cache folder.

What I want to do is to run java -cp /Users/byron1st/cache -Xbootclasspath/p: /Users/byron1st/cache framework.PFSystemMain

(The reason that I use Xbootclasspath/p: is that I have some instrumented classes to log.)

This code cannot run the process and just produce an error message meaning "It cannot find or load a default class called '.Users.byron1st.cache'". (I'm sorry for showing the error message directly because it is written in Korean.)

What is wrong with my code to use ProcessBuilder?

回答1:

I fixed this problem. It is because of 'Xbootclasspath/p:'. I changed my code like below:

ProcessBuilder builder = new ProcessBuilder("java",
                "-cp", directory,
                "-Xbootclasspath/p:" + directory,
                "framework.PFSystemMain");

In fact, I thought -Xbootclasspath/p: and its directory path are separate arguments for processbuilder, but it is not.