

When we read a large number of bytes, the application performance will be poor, due to a large number of context switches involved.įor writing the bytes read from the URL to our local file, we'll use the write() method from the FileOutputStream class: try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL). This context switch is expensive from a performance perspective. This post provides an overview of some of the available alternatives to accomplish this.

When the JVM invokes the read() system call, the program execution context switches from user mode to kernel mode and back. There are several ways to download a file from an URL in Java. When reading one byte at a time using the read() method, each method call implies a system call to the underlying file system. The performance increase comes from buffering. When reading from an InputStream, it's recommended to wrap it in a BufferedInputStream to increase the performance.

BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream())
