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.
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:
- Channel & Buffers: In the 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 is read from a channel to a buffer
- 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
- Non-blocking I/O: Here the application immediately returns the available data and the 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 I/O vs. NIO
- The 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 the 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 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!
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
.
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.
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
.
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
.
A new pop window will open where we will enter the package name as: 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
.
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
.
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!
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.
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.
You can download the full source code of this example here: JavaNioDeleteFile