How to download and save a file from Internet using Java?

URL website = new URL(“http://www.website.com/information.asp”);

ReadableByteChannel rbc = Channels.newChannel(website.openStream());

FileOutputStream fos = new FileOutputStream("information.html");

fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

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.

Use apache commons-io, just one line code:

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

public void saveUrl(String filename, String urlString)
throws MalformedURLException, IOException
{
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);

        byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1)
        {
            fout.write(data, 0, count);
        }
    }
    finally
    {
        if (in != null)
            in.close();
        if (fout != null)
            fout.close();
    }
}