Downloading a file using Channel

suggest change

If the file already exists, it will be overwritten!

String fileName     = "file.zip";                  // name of the file
String urlToGetFrom = "http://www.mywebsite.com/"; // URL to get it from
String pathToSaveTo = "C:\\Users\\user\\";         // where to put it

//If the file already exists, it will be overwritten!

//Opening OutputStream to the destination file
try (ReadableByteChannel rbc =
        Channels.newChannel(new URL(urlToGetFrom + fileName).openStream())) {
    try (FileChannel channel =
            new FileOutputStream(pathToSaveTo + fileName).getChannel()) {
        long position = 0;
        long transferred;
        while ((transferred = channel.transferFrom(rbc, position, Long.MAX_VALUE)) > 0) {
            position += transferred;
        }
    }
    catch (FileNotFoundException e) { /* Output directory not found */ }
    catch (IOException e)           { /* File IO error */ }
}
catch (MalformedURLException e)     { /* URL is malformed */ }
catch (IOException e)               { /* IO error connecting to website */ }

Notes

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents