File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Writing data into file from URL address Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Writing data into file from URL address" Watch "Writing data into file from URL address" New topic

Writing data into file from URL address

Siim Karu

Joined: Sep 16, 2003
Posts: 3

I need to download file from certain url address and write it to file on my local disk. The file being downloaded is a image file and therefore
I cannot make sure what encoding should I use. When I save file manually on disk and compare it with the file written programmatically, then
the bytes in both files are not equal. Any smart advises are welcome.

The code being used is:


public class UrlParser {

public static void main(String[] args) {

String data;
// Construct a URL object
URL url = new URL("");

// Open a connection to the URL object
String encoding = "UTF8";
BufferedReader html = new BufferedReader(new InputStreamReader(url.openStream(),encoding));
Writer img_out = new OutputStreamWriter(new FileOutputStream("sc.gif"), encoding);

while((data = html.readLine()) != null) {
img_out.write( data );

} catch(MalformedURLException e) {
} catch(IOException e) {
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

It's a bad idea to use Readers and Writers, which are intended for use with character data, on binary data, like images. Change your writers to streams and let us know how it works.

[How To Ask Questions On JavaRanch]
I agree. Here's the link:
subject: Writing data into file from URL address
It's not a secret anymore!