-1

Possible Duplicate:
Best way to read structured binary files with Java

I used to be a c programmer. In c, if I want to transfer binary data (not just text file) from std io, I can just do it by calling getchar() and putchar()over and over again, until reaching EOF. My question is that is that possible to do the same way in Java? Can I just call readline() and writeline() over and over again? If not, what can I do?
Thank you!

Community
  • 1
  • 1
Junfei Wang
  • 578
  • 1
  • 13
  • 26

1 Answers1

5

No, you should absolutely not use anything with readLine() and writeLine() calls. Those are for text data. If you're transferring binary data, you should be using InputStream and OutputStream - nothing with Reader or Writer in the name. If you convert binary data to text, you're almost guaranteed to lose data.

But then you can just copy blocks of data at a time:

public static void copy(InputStream input, OutputStream output)
    throws IOException {
   byte[] buffer = new byte[16 * 1024]; // For example...
   int bytesRead;
   while ((bytesRead = input.read(buffer)) > 0) {
     output.write(buffer, 0, bytesRead);
   }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194