c.wilson
c.wilson

Reputation: 1

Java ProcessBuilder issue

I am having trouble using the > operator to write to file in Process Builder. The actual process will run fine and let me parse using a InputStreamReader etc to parse the output. I want the process to be written to file using command line like >test.json for example.

Here is my code

try {
    //process builder used to run a Python script 
    ProcessBuilder process = new ProcessBuilder("python",
    System.getProperty("user.dir")+"\\createJson.py","--structure","cloc.csv",
                                  "--weights","EntityEffort.csv",">","a.json");

    process.directory(new File("c:\\users\\chris\\desktop\\test2"));
    Process p = process.start();

} catch(Exception e) {
    e.printStackTrace();
}

Upvotes: 0

Views: 764

Answers (1)

slim
slim

Reputation: 41223

As @JimGarrison points out, > is interpreted by the shell. Here you are directly starting a process for createJson.py, without a shell.

In UNIX you could use ProcessBuilder to start a shell using:

process = new ProcessBuilder("bash", "someCommand", ">", "outputfile");

Something similar will probably work with Windows and cmd.exe.

However, it's not very good practice. It's an opportunity for command injection attacks. Calling external processes is a last-resort approach, and you should try and minimise what you do within those processes.

So you would be better off sticking with what you have, and handle the redirect to file in Java. The ProcessBuilder javadoc gives an example:

File log = new File("log");
processBuilder.redirectOutput(Redirect.appendTo(log));

Upvotes: 2

Related Questions