3

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!

rustybeanstalk
  • 2,722
  • 9
  • 37
  • 57

2 Answers2

6

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);
    }
}
Cacovsky
  • 2,536
  • 3
  • 23
  • 27
RHT
  • 4,974
  • 3
  • 26
  • 32
  • Output stream is clear - I can make an FileOutputStream for that. How do I turn my BufferedReader into a InputStream? – rustybeanstalk Oct 20 '11 at 01:36
  • Why do you have to use a reader? Why can't you use InputStream directly to get the bytes? – RHT Oct 20 '11 at 01:49
  • @thehanseatic You don't turn your `BufferedReader` into an `InputStream`. You *start* with an `InputStream`. As you have binary data, using a `BufferedReader` is incorrect. – user207421 Oct 20 '11 at 04:22
  • Thank you very much for clearing up the confusion. I have gotten it to work using the method above. – rustybeanstalk Oct 21 '11 at 06:58
1

Start with Basic I/O then do the i, then the o, or if you want to conserve memory i/o, i/o i/o (rinse and repeat till no more i).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433