You can use apache commons IO library. It's easy. I have used it in many projects.

File dstFile = null;
// check the directory for existence.
String dstFolder = LOCAL_FILE.substring(0,LOCAL_FILE.lastIndexOf(File.separator));
if(!(dstFolder.endsWith(File.separator) || dstFolder.endsWith("/")))
    dstFolder += File.separator;

// Creates the destination folder if doesn't not exists
dstFile = new File(dstFolder);
if (!dstFile.exists()) {
    dstFile.mkdirs();
}
try {
    URL url = new URL(URL_LOCATION);
    FileUtils.copyURLToFile(url, dstFile);
} catch (Exception e) {
    System.err.println(e);
    VeBLogger.getInstance().log( e.getMessage());
}
Answer from bitkot on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 47505245 › how-to-download-large-data-file-by-java-code-where-data-is-fetching-in-chunks
How to download large data file by java code where data is fetching in chunks? - Stack Overflow
Java Streams looks very suitable option after taking your use case in consideration. Processing file is based on Java streams yield better results as compared to file scanner , Buffered Reader or Java NIO using memory mapped files. Here is performance comparison of processing ability of various Java Alternatives: ... package com.large.file; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; public class Java8StreamRead { pub
Discussions

how to download large files without memory issues in java - Stack Overflow
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I... More on stackoverflow.com
🌐 stackoverflow.com
url - downloading a large file in java - Stack Overflow
I can download file with your code. Check your network firewall ... Find the answer to your question by asking. More on stackoverflow.com
🌐 stackoverflow.com
Download large file through java client in HTTP - Stack Overflow
Is there any way to download large file (like 1 GB) from without buffering which means what ever streams are coming I could directly write it into a file on local machine. As for the large file mem... More on stackoverflow.com
🌐 stackoverflow.com
April 26, 2012
Download Large Files using java - Stack Overflow
I am building an application in which I want to download large files on handset (mobile), but if size of file is large I am getting exception socket exception-broken pipe. More on stackoverflow.com
🌐 stackoverflow.com
May 13, 2010
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - We’ve seen in this article several ways to download a file from a URL in Java. The most common implementation is to buffer the bytes when performing the read/write operations. This implementation is safe to use even for large files because we don’t load the whole file into memory.
🌐
Stack Overflow
stackoverflow.com › questions › 38199388 › downloading-a-large-file-in-java
url - downloading a large file in java - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. here is my code for downloading a file from a webpage and saving it in a path: Copyimport java.io.File; import java.io.IOException; import java.net.URL; import org.apache.commons.io.FileUtils; public class Demo2 { public static void main(String...args){ try { URL url = new URL("ftp://ftp.fu-berlin.de/pub/misc/movies/database/crazy-credits.list.gz"); FileUtils.copyURLToFile(url, new File("D:\\imdb\\credits.list.gz")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
🌐
CopyProgramming
copyprogramming.com › howto › how-to-download-large-data-file-by-java-code-where-data-is-fetching-in-chunks
Java: Java code to download large data files in chunks: A step-by-step guide
May 14, 2023 - The answer can be found on this website, and you can refer to the complete tutorial for more information. Access the Java Download Manager by visiting the website luugiathuy.com in March 2011. Java - download a file from Spring boot rest service, with the help of js-file-download you can trigger browser to save data to file as if it was downloaded.
🌐
Java-forums
java-forums.org › new-java › 55044-download-large-files-web.html
Download large files from web
February 4, 2012 - I have a problem, when I want to download a big file, with this code I only download a small part of this file: ... int DownloadProgress = 0; File file = new File("/" + ZipName); boolean exists = file.exists(); if (Update == true) { if (!exists) { try { URL GameURL = new URL(ZipURL); GameURL.openConnection(); InputStream InputFile = GameURL.openStream(); FileOutputStream OutputFolder = new FileOutputStream(ZipName); byte[] buffer = new byte[153600]; int totalBytesRead = 0; int bytesRead = 0; ProgressMonitor progressMonitor = new ProgressMonitor(null, "Downloading...", "Preogress", 0, 100); whi
🌐
amitph
amitph.com › home › java › how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - Next, we use a bucket of byte[] to read 2048 bytes from the input stream and write it onto the output stream iteratively. This example demonstrates how we can use our own buffer (for example 2048 bytes) so that downloading large files should not consume huge memory on our system. Note: While dealing with Java File IO, we must close all the open streams and readers.
Find elsewhere
🌐
Google Groups
groups.google.com › g › microprofile › c › dP-KGmwVRkI
How to download large files (>1GB) with Java
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... you shouldn't return tye byte[] but the Stream straight, in this way the 1GB file won't be loaded into memory. Maybe StreamingOutput api can help.
🌐
E-zest
blog.e-zest.com › downloading-large-files-through-web-service
Downloading Large Files through Web Service
Only the remaining file should be downloaded. But not the complete file. Max file size supported = Java int range. Files upto 19 MB are tested with this solution. The solution is still under testing and is subject to change. The WA application breaks Large File in five files.
🌐
Stack Overflow
stackoverflow.com › questions › 10335179 › download-large-file-through-java-client-in-http
Download large file through java client in HTTP - Stack Overflow
April 26, 2012 - Is there any way to download large file (like 1 GB) from without buffering which means what ever streams are coming I could directly write it into a file on local machine. As for the large file mem...
🌐
Coderanch
coderanch.com › t › 640669 › java › Download-Large-files-Servlet-Tomcat
Download Large files using Servlet / Tomcat (Servlets forum at Coderanch)
October 16, 2016 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Hi, We have a website used for downloading large files as large as 6gb and sometimes larger.
Top answer
1 of 1
5

Correctness

Files over 10240 bytes will fail to download because the streams are closed after one iteration of the while loop(Edit: Was paste error by OP). As of java 7, it is highly preferable to use a try-with-resources block when working with AutoCloseable objects.

Implementation

Wrapping your FileOutputStream in a BufferedOutputStream would be preferable to manually flushing.

Performance

You may see some performance gain by running each file download on its own thread. You'd need to take your existing code and move much of it into a Runnable or Callable. Use an Executor to perform some or all of the downloads concurrently.

If you made these modifications, the code might look more like:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class FileDownloader {

    // or newFixedThreadPool() to control the number of threads.
    private final ExecutorService executor = Executors.newCachedThreadPool();

    public FileDownloader() {
        super();
    }

    public void downloadPdf(final URL targetUrl) throws IOException {
        final File destination = File.createTempFile("download-pdf-" + System.currentTimeMillis(), ".pdf");
        this.executor.submit(new DownloadCallable(targetUrl, destination));
    }

    private static final class DownloadCallable implements Callable<File> {

        private static final int BUFFER_SIZE = 1024 * 1024;

        private final URL targetUrl;
        private final File destination;

        public DownloadCallable(final URL targetUrl, final File destination) {
            this.targetUrl = targetUrl;
            Objects.requireNonNull(targetUrl);

            this.destination = destination;
            Objects.requireNonNull(destination);
        }

        @Override
        public File call() throws IOException {
            final URLConnection request = this.targetUrl.openConnection();
            try (final InputStream inputStream = request.getInputStream();
                    final FileOutputStream fileStream = new FileOutputStream(this.destination);
                    final BufferedOutputStream outputStream = new BufferedOutputStream(fileStream, BUFFER_SIZE);) {

                final byte[] data = new byte[10240];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, bytesRead);
                }
            }
            return this.destination;
        }
    }
}
🌐
javathinking
javathinking.com › blog › how-can-i-download-and-save-a-file-from-the-internet-using-java
How to Download and Save a File from a URL Using Java: Step-by-Step Guide — javathinking.com
import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class NioFileDownloader { public static void main(String[] args) { String fileUrl = "https://example.com/large-file.zip"; // Replace with your URL String savePath = "downloads/large-file.zip"; // Local path try { URL url = new URL(fileUrl); // Step 1: Create URL // Step 2: Open input stream and Step 3: Copy to file try (InputStream inputStream = url.o
🌐
Medium
pkslow.medium.com › multiple-ways-to-download-files-from-internet-in-java-ced5d3aaae2c
Multiple Ways to Download Files from Internet in Java | by Larry Deng | Medium
April 3, 2023 - We use BufferedInputStream to read and FileOutputStream to write to the local file: private static void javaIO() { try { try (BufferedInputStream in = new BufferedInputStream(new URL(URL).openStream()); FileOutputStream fileOutputStream = new ...
🌐
amitph
amitph.com › home › spring › downloading large files using spring webclient
Downloading Large Files using Spring WebClient - amitph
November 22, 2024 - Remember that, increasing DataBuffer size will increase its impact on your overall memory. We should only do so when we have specific requirements. The best way to download large files using WebClient it to download the file in chunks.