0

I am currently writing a lot of text to a file using a BufferedWriter. I pass the BufferedWriter object around to various functions in my code. I now need to use a stream object in my functions in order to use the Base64OutputStream class in one place. I'm unsure how to change all of my code without needing to convert strings to bytes for every .write() call and also avoid calling helper functions like IOUtils.write() since that sounds like it would impact performance.

Shall I just give in and call the IOUtils.write() function for the string writes? The code is certainly ugly compared to a clean call to a stream or writer write() function.

Could I create both a stream object and a writer object and pass both around, switching between them as needed (which sounds like it would just crash or cause corruption)?

Java is a second language for me so I don't know off the top of my head all of the possible classes and functions available to me. I would like the code to be as readable and maintainable as possible.

1 Answer 1

1

An OutputStreamWriter is a bridge from character streams to byte streams

So you can create an OutputStream, wrap it in an OutputStreamWriter, and writing to the OutputStreamWriter will encode characters to bytes and call the corresponding OutputStream.write.

In this specific case do note that documentation says

It is mandatory to close the [Base64OutputStream] after the last byte has been written to it, otherwise the final padding will be omitted and the resulting data will be incomplete/inconsistent

which closes the underlying stream in turn. So if writing to Base64OutputStream isn't your last operation, you may need to close and reopen the original stream, invalidating the Writer.

1
  • I missed the requirement to close the Base64OutputStream. Since that is the case and I need to write the base64 data to a temporary file then write that to the final output file (being an XML file with base64 inside of a tag), I can go back to using a file writer that supports writing strings directly. Thanks. Commented Oct 2, 2017 at 21:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.