• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writing data into file from URL address

 
Siim Karu
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

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;
try{
// 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 );
}
img_out.close();

} catch(MalformedURLException e) {
System.out.println(e);
} catch(IOException e) {
System.out.println(e);
}
}
}
 
Joe Ess
Bartender
Pie
Posts: 9257
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic