jQuery in Action, 3rd edition
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
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:

import java.net.*;
import java.io.*;

public class UrlParser {

public static void main(String[] args) {

String data;
// Construct a URL object
URL url = new URL("http://stockcharts.com/c-sc/sc?s=qqqq&p=D&b=3&g=0&i=t74934638175&r=4028");

// 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: 9168

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]
subject: Writing data into file from URL address
jQuery in Action, 3rd edition