What is the preferred way of piping information into another process in Java?

95 views Asked by At

I need to pipe data into another process. The data is an array of strings that I concatenated into one large string. The external process accepts a text file. Currently, I am writing the string into a ByteArrayOutputStream but is there a better way to do this?

public OutputStream generateBoxFile() throws IOException {
    OutputStream boxStream = new ByteArrayOutputStream();
    for (String boxLine : boxLines) {
        boxLine += "\n";
        boxStream.write(boxLine.getBytes(Charset.forName("UTF-8")));
    }
    return boxStream;
}

EDIT: For further clarifications, I am launching a program called trainer which accepts a text file. So I would invoke this program like this in the shell ./trainer textfile. However, I want to do everything in memory, so I'm looking for a good way to write data into a temporary file that is not on disk and then feed this into trainer.

2

There are 2 answers

6
Peter Lawrey On BEST ANSWER

The simplest way to write a collection String to a file is to use a PrintWriter

public static void writeToFile(String filename, Iterable<String> strings) {
    try (PrintWriter pw = new PrintWriter(filename)) {
       for(String str : strings)
            pw.println(str);
    }
}

If you need to write UTF-8 you can change the encoding with

try (PrintWriter pw = new PrintWriter(
                      new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")) {
0
Andy Thomas On

You can easily pipe data to a process you've launched through its standard input stream. In the parent process, you can access the child's standard input stream through Process.getOutputStream().

This does require your child process to accept data through standard input rather than a file. Your child process currently gets its input from a file. Fortunately, you note in a comment that you own the code of the child process.