Saturday, 9 July 2022

How to download a binary file in Java?

Approach 1: Using InputStream, we can read the data from the given url and OutputStream can be used to write the binary data to disk.

 


 

Find the below working application.

 

BinaryDownloaderDemo.java

package com.sample.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class BinaryDownloaderDemo {

	private static void downloadFile(final String urlToDownload, final String filePath) {
		
		// Create parent folders if not exists
		final File file = new File(filePath);
		file.getParentFile().mkdirs();

		try {
			final URL url = new URL(urlToDownload);
			final URLConnection urlConnection = url.openConnection();

			try (final InputStream inputStream = urlConnection.getInputStream();
					final OutputStream outputStream = new FileOutputStream(filePath);) {
				byte[] buffer = new byte[65535];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		final String urlToDownlaod =  "https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.zip";
		
		downloadFile(urlToDownlaod, "/Users/Shared/softwares/maven/apache-maven-3.8.6-bin.zip");
		
	}

}

 

Approach 2: Using nio FileChannel# transferFrom method.

 

BinaryDownloaderDemo2.java

package com.sample.app;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class BinaryDownloaderDemo2 {

	private static void downloadFile(final String urlToDownload, final String filePath) {

		// Create parent folders if not exists
		final File file = new File(filePath);
		file.getParentFile().mkdirs();

		try {
			URL website = new URL(urlToDownload);

			try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
					FileOutputStream fos = new FileOutputStream(filePath);) {
				fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		final String urlToDownlaod = "https://dlcdn.apache.org/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.zip";

		downloadFile(urlToDownlaod, "/Users/Shared/softwares/maven/apache-maven-3.8.6-bin.zip");

	}

}

 

 

 

You may like

File programs in Java

Count number of lines in a file

Download file from Internet using Java

Get the content of resource file as string

Copy the content of file to other location

Write byte array to a file

No comments:

Post a Comment