Java Nio Delete File Example

If developers are working on a Java Swing or a desktop application then it may be required that sometimes developers need to delete a file from the file system. This tutorial is to learn about handling the files using the Java Nio package and shows how to delete a file in Java using the Nio package.
 
 
 
 
 
 
 
 

Want to be a Java NIO Master ?
Subscribe to our newsletter and download the JDBC Ultimate Guide right now!
In order to help you master Java NIO Library, we have compiled a kick-ass guide with all the major Java NIO features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

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 increase in the operational speed.

Java Nio consists of the following core components:

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 I/O vs. NIO

Now, open up the Eclipse IDE and let’s see how to implement a simple delete operation with Java Nio package!

2. Java Nio Delete 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. 3: Delete 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. 4: 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. 5: 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. 6: 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>JavaNioDeleteFile</groupId>
	<artifactId>JavaNioDeleteFile</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. 7: Java Package Creation

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

Fig. 8: 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. 9: Java Class Creation

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

Fig. 10: Java Class (FileDeleteExample.java)

3.1.1 Implementation of Utility Class

The Files.delete() method is defined with the following signature,

public static void delete(Path path) throws IOException

Where the only input parameter is the path which is an instance of java.nio.file.Path. Files.delete() method deletes the file specified using the java.nio.file.Path instance. Since the delete() method doesn’t return anything when it is successful, hence, the method successfully deleted the file from the path passed as an argument to the method. When no instance of the file is present (i.e. the file being deleted doesn’t exist), a NoSuchFileException is thrown and if something else goes wrong, an IOException may get thrown.

Add the following code to it:

FileDeleteExample.java

package com.jcg.java.nio;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDeleteExample {
	private static String file_path = "config/sample.txt";
	// STEP #1 - File Exists - This Method Will Delete The File From The Configured Path.
	private static void fileExists() {
		Path filePath = Paths.get(file_path);
		System.out.println("STEP #1" + "\n\n" +"File Exists Before Delete?= " + Files.exists(filePath));
		try {
			System.out.println("! Deleting File From The Configured Path !");
			Files.delete(filePath);
		} catch(IOException ioException) {
			ioException.printStackTrace();
		}
		System.out.println("File Exists After Delete?= " + Files.exists(filePath));
	}
	// STEP #2 - File Doesn't Exists - This Method Will Throw The 'NoSuchFileException'.
	private static void fileDoesnotExists() {
		System.out.println("\n" + "STEP #2" + "\n");
		Path filePath = Paths.get(file_path);
		try {
			Files.delete(filePath);
		} catch (IOException ioException) {
			System.out.println("! Error Caught In Deleting File As The File Is Not Present !");
			ioException.printStackTrace();
		}
	}
	public static void main(String[] args) {
		fileExists();		
		fileDoesnotExists();
	}
}

4. Run the Application

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

Fig. 11: Run Application

5. Project Demo

In the above code, we have used the Files.delete() method to delete a sample file in the project and the code shows the status as output.

Fig. 12: 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 delete 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: JavaNioDeleteFile
Exit mobile version