Tuesday, December 4, 2012

How to download and save a file from url using Java

Give a try to Java NIO:

try {
    URL url = new URL("http://portal.com/img/logo-header.gif");
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fileOutputStream = new FileOutputStream("C:\\src\\a.gif");
    fileOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (Exception ex) {
    ex.printStackTrace();
}

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html 

No comments:

Post a Comment