Tuesday, June 23, 2009

Java: get a file from URL

The following code show how to get a file from URL


URL serviceUrl = new URL("http://www.hoax-slayer.com/images/north-pole-moon2.jpg");
URLConnection urlConn = serviceUrl.openConnection();
InputStream is = serviceUrl.openStream();
FileOutputStream fos = new FileOutputStream("/tmp/myfile.tmp");

int aChar;
while ((aChar = is.read()) != -1) {
fos.write(aChar);
}

is.close();
fos.close();

If you want to save in original file name then you can add the code

String filename;
StringTokenizer tokenizer = new StringTokenizer(serviceUrl.getFile(), "/");
while (tokenizer.hasMoreTokens()) {
filename = tokenizer.nextToken();
}

before code
FileOutputStream fos = new FileOutputStream("/tmp/myfile.tmp");
do not forget to change name to filename variable