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
.
The simplest way to write a collection String to a file is to use a PrintWriter
If you need to write UTF-8 you can change the encoding with