I’m trying to upload a file via URLConnection, but I need to read/write it as a binary file without any encoding changes.
So i’ve tried to read byte[] array from a FileInputStream, but now i have an issue. The PrintWriter object I use for outputing to the server does not allow me to do writer.write(content) (where content is of type byte[]). How can i fix this? Or is there another way to quickly copy binary data from a FileInputStream to a PrintWriter?
Thank you
Writerobjects (includingPrintWriter) are intended specifically for output of character data. It sounds like you want anOutputStreaminstead of aWriterhere.Where did your
PrintWritercome from? If it was created by wrapping some kind ofOutputStreamwith anOutputStreamWriterand then wrapping that with aPrintWriter, then you should just use the originalwrite(byte[] b)method from the originalOutputStream, rather than trying to use aWriter.If you want to mix character output and byte output, you may need to use
String.getBytes(). Check out this example:(Of course, this will only work if the system that is reading your output understands that you are writing a mixture of characters and raw bytes and knows how to handle the mixed data that you are sending it.)