Search code examples
javaterminalprocessprocessbuilder

Java ProcessBuilder output to create image file


I am currently using ProcessBuilder in java to run a python script as if I was doing it in the terminal. This python script should create an image and in terminal I would do it like this

python3 script.py arg1 arg2 > out.png

The problem here is that processbuilder does not allow me to add the '>' (redirect the output) char in the arguments followed by the path to my out.png file.

It currently creates an output with strange chars (I assume it is a base64 string).

A bit of my current code:

File output = new File("/Users/myuser/Desktop/OUTXXXXXXXXX.png");
ProcessBuilder pb =
    new ProcessBuilder("/usr/local/bin/python3", pythonScriptLocation",
        fileOneLocation, fileTwoLocation);
pb.redirectInput(output);
Process process = pb.inheritIO().start();
int errCode = process.waitFor();
System.out.println("Command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));

All variables used above are declared.

Already seen this approach but it did not create any file at all.

EDIT:

With redirectOutput method:

File output = new File("/Users/myuser/Desktop/OUTXXXXXXXXX.png");
ProcessBuilder pb =
    new ProcessBuilder("/usr/local/bin/python3", pythonScriptLocation",
        fileOneLocation, fileTwoLocation);

File stdoutFile = new File("/Users/mysuer/Desktop/outxx.png");
pb.redirectOutput(stdoutFile);
Process process = pb.inheritIO().start();
int errCode = process.waitFor();
System.out.println("Command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));

Solution

  • You should stop your Java process from inheriting the IO from your Python process (stop calling pb.inheritIO()). Once you've done it, you can redirect the output of the process as:

    File stdoutFile = new File("out.png");
    redirectOutput(output);