javaioexternal-process

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


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.


Solution

  • 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")) {