Search code examples
javaprocessbuilder

Process builder won't find my file


I am trying to compile a java program using the ProcessBuilder but everytime i see this error being present on the console even though the file is present at that path.

ERROR

java.io.IOException: Cannot run program "javac /Users/foo/Desktop/online-compiler/user1455523443383/Main.java": error=2, No such file or directory

@Override
    public ProgramResult executeProgram(File program) throws IOException {
        String parent = program.getParentFile().getParentFile().getAbsolutePath();
        String[] commands = new String[]{
            "javac "+program.getAbsolutePath(),
//            "cd "+parent,
//            "java -cp  "+parent+" "+PACKAGE_NAME+"."+MAIN_CLASS
        };

        ProcessBuilder builder = new ProcessBuilder(commands);
        builder.redirectErrorStream(true);

        Process executorProcess = builder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(executorProcess.getInputStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while((line = reader.readLine())!=null) {
            sb.append(line);
        }
        reader.close();

        ProgramResult result = new ProgramResult();
        result.setOutput(sb.toString());

        return result;
    }

Some more information

Javac is on the path, as running it(without the file) via ProcessBuilder is printing the help options.

OS : MACOSX

Conclusions from this questions are

1) ProcessBuilder needs every argument to the command as a separate index , like to execute "javac filename.java" you write this

new String[] {"javac" , "filename.java"}

2) To execute multiple commands you should be using the following trick

new String[]{
               "/bin/bash",
                "-c",
                "javac "+
                program.getAbsolutePath()+
                " &&" +
                " java -cp " +
                parent +
                " "+ PACKAGE_NAME+"."+MAIN_CLASS,
}

A big thanks to @kucing_terbang for really digging in this problem with me to solve it.


Solution

  • AFAIK, if you want to put an argument into the ProcessBuilder, you should put in into another index of the array.

    So, try change the command variable into something like this and try again.

    String[] commands = new String[]{"javac", program.getAbsolutePath()};