Andrei Ermicioi's Blog

Just another WordPress.com weblog

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

Advertisements

Written by eraniblog

April 20, 2010 at 13:15

Posted in Coding

%d bloggers like this: