nio

Java Nio Download File From Url Example

Java NIO (i.e. new I/O) is an interesting file input-output mechanism introduced in Java 5 and provides the different way of working with the input-output operations than the standard input-output API’s. Java NIO supports a buffer-oriented, channel-based approach for the I/O operations and with the introduction of Java 7, the NIO system has expanded thereby providing the enhanced support for the file system features and the file handling mechanism. In this tutorial, we will see how to download a file from the URL in Java.
 
 
 

1. Introduction

Java NIO was developed to allow the Java programmers implement the high-speed input-output operations without using the custom native code. NIO moves the time-taking I/O activities like filling, namely and draining buffers etc back into the operating system, thus allows the great increase in the operational speed.

Java NIO consists of the following core components:

  • Channel & Buffers: In standard, I/O API the character streams and the byte streams are used but in NIO, developers work with the channels and buffers. In this case, the data is always written from a buffer to a channel and read from a channel to a buffer

    Fig. 1: Channel & Buffers
    Fig. 1: Channel & Buffers
  • Selectors: It is an object that can be used for monitoring the multiple channels for events like data arrived, connection opened etc. Thus, a single thread can monitor the multiple channels for the data

    Fig. 2: A Thread uses a Selector to handle 3 Channel's
    Fig. 2: A Thread uses a Selector to handle 3 Channel’s
  • Non-blocking I/O: Here the application immediately returns the available data and application should have a pooling mechanism to find out when more data is available

Do note, Java NIO has more components and classes but the Channel, Buffer, and Selector are used as the core of the API.

1.1 Java NIO Components

The Java NIO classes are contained in the java.nio package and it is important to understand that the NIO subsystem does not replace the existing stream-based available in java.io package. The important NIO classes are grouped under different categories that are shown below:

Fig. 3: NIO Components
Fig. 3: NIO Components

Let us understand the important classes contained in these groups.

Package Purpose
java.nio It is a top-level package for NIO system. The various types of buffers are encapsulated by this NIO system.
java.nio.charset It encapsulates the character sets and also supports the encoders and decoders that converts the characters to bytes and bytes to characters.
java.nio.charset.spi It supports the service provider for the character sets.
java.nio.channels It supports the channel which is essentially open for the I/O connections.
java.nio.channels.spi It supports the service providers for the channels.
java.nio.file It provides the support for the files.
java.nio.file.spi It supports the service providers for the file system.
java.nio.file.attribute It provides the support for the file attributes.

1.2 Java I/O vs. NIO

  • First main difference between the standard IO and NIO is that the standard IO is stream-oriented and the NIO is buffer-oriented. Buffer oriented operations provide flexibility in handling data and in buffer oriented NIO, the data is first to read into a buffer and then it is made available for processing. So we can move back and forth in the buffer. But in the case of streams, it is not possible
  • The second main difference is the blocking and the non-blocking IO operations. In case of streams, a thread will be blocked until it completes the IO operation. Wherein the NIO allows for the non-blocking operations. If the data is not available for IO operations, then the thread can do something else and it doesn’t need to stay in the locked mode. With channels and selectors, a single thread can manage the multiple threads and the parallel IO operations

Now, open up the Eclipse IDE and let’s see how to download a file with Java Nio package!

2. Java Nio Download File from Url Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 4: Download File Application Project Structure
Fig. 4: Download File Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 5: Create Maven Project
Fig. 5: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 6: Project Details
Fig. 6: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 7: Archetype Parameters
Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaNioDownloadFile</groupId>
	<artifactId>JavaNioDownloadFile</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want like JUnit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation
Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.nio.

Fig. 9: Java Package Name (com.jcg.java.nio)
Fig. 9: Java Package Name (com.jcg.java.nio)

Once the package is created in the application, we will need to create the implementation class. Right-click on the newly created package: New -> Class.

Fig. 10: Java Class Creation
Fig. 10: Java Class Creation

A new pop window will open and enter the file name as: DownloadFileFromUrl. The implementation class will be created inside the package: com.jcg.java.nio.

Fig. 11: Java Class (DownloadFileFromUrl.java)
Fig. 11: Java Class (DownloadFileFromUrl.java)

3.1.1 Implementation of Utility Class

There are different ways to download a file from a URL and some of them are:

In case of Java Nio, developers will use the URL and the ReadableByteChannel object to read the data from the URL and the FileOutputStream object to write the data in the file. Add the following code to it:

DownloadFileFromUrl.java

package com.jcg.java.nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DownloadFileFromUrl {

	// File Location
	private static String filePath ="config/sample.txt";

	// Sample Url Location
	private static String sampleUrl = "http://www.google.com";

	// This Method Is Used To Download A Sample File From The Url
	private static void downloadFileFromUrlUsingNio() {

		URL urlObj = null;
		ReadableByteChannel rbcObj = null;
		FileOutputStream fOutStream  = null;

		// Checking If The File Exists At The Specified Location Or Not
		Path filePathObj = Paths.get(filePath);
		boolean fileExists = Files.exists(filePathObj);
		if(fileExists) {
			try {
				urlObj = new URL(sampleUrl);
				rbcObj = Channels.newChannel(urlObj.openStream());
				fOutStream = new FileOutputStream(filePath);

				fOutStream.getChannel().transferFrom(rbcObj, 0, Long.MAX_VALUE);
				System.out.println("! File Successfully Downloaded From The Url !");
			} catch (IOException ioExObj) {
				System.out.println("Problem Occured While Downloading The File= " + ioExObj.getMessage());				
			} finally {
				try {
					if(fOutStream != null){
						fOutStream.close();
					}
					if(rbcObj != null) {
						rbcObj.close();
					}
				} catch (IOException ioExObj) {
					System.out.println("Problem Occured While Closing The Object= " + ioExObj.getMessage());
				}				
			}
		} else {
			System.out.println("File Not Present! Please Check!");
		}
	}

	public static void main(String[] args) {
		downloadFileFromUrlUsingNio();
	}
}

4. Run the Application

To run the Java Nio application, Right-click on the DownloadFileFromUrl class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 12: Run Application
Fig. 12: Run Application

5. Project Demo

When developers run the above program, the file will be downloaded to the mentioned directory and the code shows the following status as output.

Fig. 13: Application Output
Fig. 13: Application Output

That’s all for this post. Happy Learning!!

6. Conclusion

This tutorial uses a simple example to illustrate the functionality of the Java Nio package and helps developers understand how they can download a file from a URL in Java. That’s all for this tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Java Nio for the beginners.

Download
You can download the full source code of this example here: JavaNioDownloadFile

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Valdir
Valdir
3 years ago

No file to download. Server replied HTTP code: 403

Back to top button