views:

113

answers:

2

In java I need to read a binary file from a site and write it to a disk file. This example http://java.sun.com/docs/books/tutorial/networking/urls/readingURL.html could read webpages succesfully, but when I try to read a binary file from my localhost server and write it to a disk file the contents change, corrupting the binary file. Using fc I see that 0x90 is changed to 0x3F and other changes. How do I acess the binary files (read url and write to file) without java or anything else changing ANY characters, like doing any newline conversions or character conversions or anything else, simply reading input url and writing it out as a file.

+1  A: 

Instead of wrapping an InputStreamReader and BufferedReader around the openStream(), just wrap a BufferedInputStream around it.

GregS
Thanks, it worked! Also used new BufferedOutputStream(new FileOutputStream(filename)); for the output file as well, and now the file opens successfully and is the exact same as the original. Thanks!
Andrew Zawok
A: 

The JavaDoc for java.io.InputStreamReader states:

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

In your case, you are asking the JVM to convert the bytes into chars that will be turned into Strings. This is not what you want. Instead either read the bytes directly from the java.io.InputStream or through a java.io.BufferedInputStream.

Jacob Tomaw
In general `Reader` and `Writer` classes are for reading and writing text and `InputStream` and `OutputStream` are for reading and writing bytes (binary data) without conversions.
Jesper