Badr B
Badr B

Reputation: 1435

Command Works Through Command Line, but Not When Using ProcessBuilder

I'm writing a program that includes a feature where the user can type in Java code into a text box and be able to compile and run it. The error I get is: enter image description here

The two directories shown at the top are correct, and the command works when I do it manually through command prompt from the same working directory. I'm using Windows 10, and also here's the code:

public Process compile() throws IOException {
    save(); //saves changes to source file
    System.out.println(file.getCanonicalPath());
    ProcessBuilder processBuilder = new ProcessBuilder("javac", file.getCanonicalPath());
    processBuilder.directory(new File(settingsFile.getJdkPath()));
    System.out.println(processBuilder.directory());
    Process process = processBuilder.start(); //Throws exception
    this.compiledFile = new File(file.getParentFile(), file.getName().replace(".java", ".class"));
    return process;
}

File to compile: enter image description here

Working directory: enter image description here

Upvotes: 1

Views: 1025

Answers (1)

4dc0
4dc0

Reputation: 453

Using this code, I was able to compile a Test.java file into a Test.class file on my Desktop.

import java.io.IOException;

public class App {

    public static Process compile() throws IOException {

        String myFilePath = "C:\\Users\\redacted\\Desktop\\Test.java";
        String javacPath = "C:\\Program Files\\Java\\jdk1.8.0_171\\bin\\javac.exe";

        ProcessBuilder processBuilder = new ProcessBuilder(javacPath, myFilePath);

        return processBuilder.start();
    }

    public static void main(String[] args) throws IOException {

        Process process = compile();

    }
}

Capture

Using String javacPath = "javac.exe"; also worked, but that could be because my JDK bin is on my PATH variable.

There is something wrong with your paths or permissions in the ProcessBuilder constructor call.

Upvotes: 2

Related Questions