Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write data to a file from a BufferedReader?

In Java...

I have data stored in a BufferedReader. (I got it as a response to an HTTP post request.)

How do I write this (binary) data to a file?

I know how to write Strings to files, but how do I take the data in the BufferedReader and put it into a file.

Thanks in advance!

like image 614
rustybeanstalk Avatar asked Jun 22 '26 08:06

rustybeanstalk


1 Answers

Do not use a Reader to get bytes. Reader is used for reading character data, not binary data. Use the InputStream directly.

void write(InputStream is, OutputStream os) throws IOException {
    byte[] buf = new byte[512]; // optimize the size of buffer to your need
    int num;
    while ((num = is.read(buf)) != -1) {
      os.write(buf, 0, num);
    }
}
like image 140
RHT Avatar answered Jun 24 '26 00:06

RHT