user11416547
user11416547

Reputation:

Is there a way to save the obtained output from a a process object's getOutPutStream() method into a file

Coming from this link "Writing to the OutputStream of Java Process/ProcessBuilder as pipe" and researching i didn't find a way to specify a path for writing a process output from getOutputStream().

BufferedReader br = new BufferedReader(new FileReader(new File("commands.txt")));
        String[] input = br.readLine().split(" ");

        String cmd =  input[0] + " " + input[1] + " " + input[3];

        System.out.println(cmd);

        Process process = Runtime.getRuntime().exec(new String[]{"bash","-c", cmd});


        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(input[3]));

        byte[] buf = new byte[1024];
        int len;

        while ( (len = in.read()) > 0) {
            // out.write();
        }

In the code the exec run a process that concatenate the results from a two files and now i want to save the result in a new file. But i cannot find how because the getOutPutStream object from process have only one method write with constructor that takes int[] as parameter. Thank you for any help in advance.

Upvotes: 0

Views: 59

Answers (1)

ddmps
ddmps

Reputation: 4380

I think you are confusing the InputStream and OutputStream in this scenario. Consider them as input/output to your code. Of what I understand, you want to take what's in your in reader and output it to out. I don't see why you'd need to use the getOutputStream of Process.

Since Java 9, there is a very simple solution for this, namely the transferTo method of Reader. In effect, you could replace everything after your Process initialization with the following:

process.getInputStream().transferTo(new FileOutputStream(input[3]))

Upvotes: 1

Related Questions