We’re streaming a CSV file from a web service. It appears that we’re losing the new line characters when streaming – the client gets the file all on a single line. Any idea what we’re doing wrong?
Code:
public static void writeFile(OutputStream out, File file) throws IOException {
BufferedReader input = new BufferedReader(new FileReader(file)); //File input stream
String line;
while ((line = input.readLine()) != null) { //Read file
out.write(line.getBytes()); //Write to output stream
out.flush();
}
input.close();
}
Don’t use
BufferedReader. You already have anOutputStreamat hands, so just get anInputStreamof the file and pipe the bytes from input to output it the usual Java IO way. This way you also don’t need to worry about newlines being eaten byBufferedReader:Using a
Reader/Writerwould involve character encoding problems if you don’t know/specify the encoding beforehand. You actually also don’t need to know about them here. So just leave it aside.To improve performance a bit more, you can always wrap the
InputStreamandOutputStreamin anBufferedInputStreamandBufferedOutputStreamrespectively.