Http download using Java NIO FileChannel

Carvia Tech | December 04, 2019 | 1 min read | 74 views

Java’s Channel should always be preferred for IO related stuff because Channel can utilize OS specific optimization while dealing with the files. An input stream can easily be converted to a FileChannel using Channels.newChannel() static factory method.

import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class HttpDownloader {

    public File download(URI uri, String fileName) throws IOException {
        Path path = Paths.get(fileName);
        long totalBytesRead = 0L;
        HttpURLConnection con = (HttpURLConnection) uri.resolve(fileName).toURL().openConnection();
        try (ReadableByteChannel rbc = Channels.newChannel(con.getInputStream());
             FileChannel fileChannel =, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE));) {
            totalBytesRead = fileChannel.transferFrom(rbc, 0, 1 << 22); // download file with max size 4MB
            System.out.println("totalBytesRead = " + totalBytesRead);
        } catch (FileNotFoundException e) {
        return path.toFile();

FileChannel utilizes OS specific optimization and hence should provide better performance in general compared to any buffered streams.

Top articles in this category:
  1. CRC32 checksum calculation Java NIO
  2. Submit Form with Java 11 HttpClient - Kotlin
  3. Allow insecure SSL in Java 11 HttpClient
  4. What is ThreadLocal in Java, where will you use this class
  5. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
  6. Is Java Pure Object Oriented Language?
  7. How will you increment each element of an Integer array, using parallel operation

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info