Andrew Zawok
Andrew Zawok

Reputation: 13

read url in binary mode in java

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.

Upvotes: 1

Views: 1387

Answers (2)

Jacob Tomaw
Jacob Tomaw

Reputation: 1391

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.

Upvotes: 0

President James K. Polk
President James K. Polk

Reputation: 41956

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

Upvotes: 1

Related Questions