Home » Core Java » nio » Java Nio Append File Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java Nio Append File 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 try to get an overview of what Java NIO is and a sample code example for the file append operation.
 
 
 
 

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, the 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 I/O classes 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.

PackagePurpose
java.nioIt is a top-level package for NIO system. The various types of buffers are encapsulated by this NIO system.
java.nio.charsetIt encapsulates the character sets and also supports the encoders and decoders that converts the characters to bytes and bytes to characters.
java.nio.charset.spiIt supports the service provider for the character sets.
java.nio.channelsIt supports the channel which is essentially open for the I/O connections.
java.nio.channels.spiIt supports the service providers for the channels.
java.nio.fileIt provides the support for the files.
java.nio.file.spiIt supports the service providers for the file system.
java.nio.file.attributeIt 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 implement a simple file append operation with Java Nio package!

2. Java Nio Append File 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: File Append Application Project Structure

Fig. 4: File Append 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>JavaNioAppend</groupId>
	<artifactId>JavaNioAppend</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: AppendToFile. The implementation class will be created inside the package: com.jcg.java.nio.

Fig. 11: Java Class (AppendToFile.java)

Fig. 11: Java Class (AppendToFile.java)

3.1.1 Implementation of Utility Class

Here is a code example of appending a line to the file. We are going to use the following Nio classes to achieve our goal:

  • java.nio.file.Files: It exposes many static methods required to operate on files, directories, etc. We are going to use this class to append the data to an existing file
  • java.nio.file.Path: It represents a file object on the file system
  • java.nio.file.Paths: It exposes the static methods to return the path object by taking a string and the URI format path
  • java.nio.file.StandardOpenOption: The StandardOpenOption.APPEND argument ensures that the content bytes are appended to the sample file

Add the following code to it:

AppendToFile.java

3package com.jcg.java.nio;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AppendToFile {

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

	// Content To Be Appended To The Existing File
	private static String contentToAppend = "\nThis Line Was Added At The End Of The File!";

	public static void main(String[] args) {

		// Checking If The File Exists At The Specified Location Or Not
		Path filePathObj = Paths.get(filePath);
		boolean fileExists = Files.exists(filePathObj);
		if(fileExists) {
			try {
				// Appending The New Data To The Existing File
				Files.write(filePathObj, contentToAppend.getBytes(), StandardOpenOption.APPEND);
				System.out.println("! Data Successfully Appended !");
			} catch (IOException ioExceptionObj) {
				System.out.println("Problem Occured While Writing To The File= " + ioExceptionObj.getMessage());
			}
		} else {
			System.out.println("File Not Present! Please Check!");
		}		
	}
}

4. Run the Application

To run the Java Nio application, Right-click on the AppendToFile 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

In the above code, we have used the Files.write() method to write the data to the existing file 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 the basic configuration required to achieve the append file operation. 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: JavaNioAppend
(No Ratings Yet)
2 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Yatin BatraByron Kiourtzoglou Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Byron Kiourtzoglou
Guest
Byron Kiourtzoglou

Nice one, keep up the good work!