BufferedWriter is not writing to ByteArrayOutputStream
java, java-io
Solution
Nothing's wrong - it's just buffering! :D
The BufferedWriter works by filtering everything you send into it into a buffer - when the buffer is full, or when the writer is closed, or flushed, (It's a Closeable, so you should absolutely close it), it sends along those buffered characters to the underlying writer.
If you want to see the underlying writer update you have to either:
1) Fill up the buffer (default size is 8k in Java)
2) Call `.flush()`
3) Call `.close()`
4) As mentioned in comments, you can do a try-with-resources to make the close implicit:
try (BufferedWriter writer = new BufferedWriter(underlyingWriter)) {
// doStuff
}
Problem
I want to convert an input stream to byte array. I know I can use IOUtils from commons-io. But I am practicing some basics in java io. I read an xml file using BufferedReader and tried writing it to a ByteArrayOutputStream using BufferedWriter. But its not working. When I write directly to the ByteArrayOutputStream its working. Whats wrong in my code? ``` try (InputStream inputStream = getClass().getResourceAsStream( "/productInventory.xml"); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(arrayOutputStream)); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));) { String line = ""; while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line); } System.out.println(arrayOutputStream.size()); } catch (IOException e) { e.printStackTrace(); } ``` When I include below line in the loop its working ``` arrayOutputStream.write(line.getBytes(), 0, line.getBytes().length); ``` What is wrong while using BufferedWriter?