Removing file in java

Removing file in java

File management (good old CRUD: create, read, update, delete) is quite common operation in software development. In this short post I would like to present 2 ways of removing files in Java.

Method available in every Java version

Every Java version provides delete() method in File class which can be used to delete file:

File filePath = new File("SomeFileToDelete.txt"); boolean success = filePath.delete();

The delete() method returns boolean value which informs whether the file was removed successfully. If the file did not exist before call, the method return false.

This method can also delete empty directory. If the directory does not exist before the call or is not empty, the method returns false.

It is important to note that this method does not throw any exception in case of failure (except SecurityException). Additionally, it does not have any way to inform why the delete operation failed.

New method since Java 7

Because of the above limitations the new static method delete() in Files class was introduced in Java 7:

Path filePath = Paths.get("SomeFileToDelete.txt"); Files.delete(filePath);

The static method Files.delete() deletes a file, empty directory or a link (not the file pointed to). The real improvement over the previous method is that it properly utilizes exceptions and reports more information about the root cause if the file/directory/link cannot be removed for some reason. The following exceptions can be reported:

  • NoSuchFileException if the file/directory/link does not exist
  • DirectoryNotEmptyException if the file is a directory and is not empty
  • IOException if an IO error occurs (e.g. missing file permissions)
  • SecurityException if the operation is not allowed by SecurityManager
Читайте также:  Запретить пробелы в php

There is an additional method Files.deleteIfExists which also deletes the file but does not throw exception NoSuchFileException if the file does not exist. This method can still throw other above exceptions to indicate error.

Common problems

Sometimes the delete operation may fail with the following error message:

The process cannot access the file because it is being used by another process

This error is quite popular on Windows and means that some process or application is still using the file (e.g. read or write to the file). Therefore, Windows operating system blocks the file removal. In order to remove the file successfully, it needs to be closed first.

Источник

Delete a File using Java IO Streams

Java Course - Mastering the Fundamentals

There are two boolean methods that can be used to delete files and directories in Java. File.delete() method of java.io package deletes the file or directory denoted by the abstract pathname. It can delete only empty directories and does not throw any exceptions.

Likewise, Files.deleteIfExists(path) method of java.nio.file package is also used to delete files and empty directories. However, this method throws two exceptions: DirectoryNotEmptyException and IOException .

Introduction

A file is a resource for recording data in a storage device like a hard disk, pen drive, etc. It is identified by its filename and location.

File Handling in Java performs various operations such as creating a file, reading its content, writing to a file, and deleting a file. Java uses the concept of a stream to make I/O (Input/Output) operations on a file. A stream is a sequence of data or objects that supports various methods.

Streams in Java are of two types, Character Stream and Byte Stream. Byte streams are used to perform input and output of 8-bit bytes. Mostly, they are used to read or write raw binary data. Character stream is used to perform read and write operations on 16-bit Unicode.

In Java, we can delete files using these two methods i.e. File.delete() and using Files.deleteIfExists() . Let us discuss each of these one by one.

Contradictory to delete operations in other operating systems or programming languages, files being deleted using the Java program are deleted permanently from the system. They are not moved to recycle bin or trash.

Method 1: Using File.delete() Method

The File class in java.io package is used to perform various operations on files such as createNewFile() , exists() , canWrite() , canRead() , etc. To delete a file using the File class, we use its delete() method. This method doesn’t take any parameters, and it returns a boolean. Let us note down a few important points regarding the delete() method in the File class.

Exceptions

  • SecurityException – If a security manager exists and its SecurityManager.checkDelete( java.lang.String ) method denies delete access to the file

Important Points

  • It is used to delete both files and empty directories. File.delete() method can delete empty directories only.
  • Returns true if and only if the file or directory is successfully deleted; false otherwise.
  • Throws only one exception, SecurityException , for the reasons mentioned above.

Let us look at an example:

Explanation:

  • In the above example, we are importing the java.io package, which contains the File class.
  • In the main() method of the class, we create temp_file object of the File class and pass the address of the file to be deleted.
  • The file can be of any format or extension. In the if statement, we call the delete() method of the File class using the temp_file object.
  • If the delete() method returns true , we print the successful custom message.
  • Else, if it returns false , we print that the file was not deleted.

The File.delete() method cannot delete a file:

  • If its path is wrong or corrupted
  • Proper delete access is not available to the user
  • Some I/O Stream error has occurred

As for deleting a file, we neither use the FileWriter class (used for writing to a file) nor the Scanner class (used for reading from a file); there’s no need to close the stream using the close() method. FileWriter and Scanner classes require the closing of the file before exiting.

Method 2: Using Files.deleteIfExists(Path path) method

Files.deleteIfExists(Path path) is a boolean method defined in java.nio.file package. This method deletes a file mentioned in the path if it exists. It also deletes a directory in the path only if the mentioned directory is empty.

It takes a path as a parameter, the path to the file/directory to be deleted. It returns true if the file was deleted by this method; false if the file could not be deleted because it did not exist.

The file couldn’t be deleted due to various reasons:

  • The file is not present in the path, or the path is invalid/does not exist.
  • I/O Stream error while deleting the file.

Exceptions

This method throws three types of exceptions to show various scenarios:

  • DirectoryNotEmptyException — If the path is a directory and could not be deleted because the directory is not empty
  • IOException — If an I/O error occurs
  • SecurityException — In the case of the default provider, and a security manager is installed, the SecurityManager.checkDelete(String) method is invoked to check to delete access to the file.

Let us now see an example:

Explanation:

  • In the above example, we import java.nio.file and java.io.IOException packages and create a Main named class.
  • In the main() method of this class, we have put try and catch blocks as our desired method deleteIfExists() throws exceptions.
  • We first try to delete the file using the method and store the result in the isDeleted variable of the boolean type.
  • If the isDeleted is true, we print a successful completion message; else, we print an unsuccessful custom message.
  • If the method throws an exception, we are catching them in the various catch blocks and displaying suitable information.

Conclusion

  • To delete a file using Java, you can use two methods i.e. File.delete() Files.deleteIfExists(path) methods defined in java.io and java.nio.file packages respectively.
  • delete() method doesn’t throws SecurityException and returns a boolean. If the file is deleted successfully, it returns true else; it returns false.
  • deleteIfExists() method throws an exception in case of I/O errors, or the given path’s directory is non-empty. It also returns a boolean, true if the file is deleted. Otherwise, it returns false.
  • Both Files.delete() and Files.deleteIfExists() can delete only empty directories.

Источник

How to Delete Files and Directories in Java

Last updated: 01 June 2020 To delete a file in Java, we can use the delete() method from Files class. We can also use the delete() method on an object which is an instance of the File class. Example:

Deleting a File Using the Files class

import java.io.IOException; import java.nio.file.*; public class DeleteFile < public static void main(String[] args) < Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt"); try < Files.delete(path); >catch (NoSuchFileException x) < System.err.format("%s: no such" + " file or directory%n", path); >catch (IOException x) < System.err.println(x); >> > 

The above code deletes a file named newFile.txt in ./src/test/resources/ directory. The multiple catch() blocks will catch any errors thrown when deleting the file.

Deleting a File Using the File Class

Instead of using the delete() method on the Files class, we can also use the delete() method on an object which is an instance of the File class. Example:

import java.io.File; public class DeleteFile < public static void main(String[] args) < File myFile = new File("./src/test/resources/newFile.txt"); if (myFile.delete()) < System.out.println("Deleted the file: " + myFile.getName()); >else < System.out.println("Failed to delete the file."); >> > 

Delete a File if Exists

import java.io.IOException; import java.nio.file.*; public class DeleteFile < public static void main(String[] args) < Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt"); try < Files.deleteIfExists(path); >catch (IOException x) < System.err.println(x); >> > 

Delete a Directory

We can use the above code to delete a folder as well. If the folder is not empty a DirectoryNotEmptyException is thrown, so we have to explicitly catch the exception.

import java.io.IOException; import java.nio.file.*; public class DeleteFile < public static void main(String[] args) < Path path = FileSystems.getDefault().getPath("./src/test/resources"); try < Files.deleteIfExists(path); >catch (NoSuchFileException x) < System.err.format("%s: no such" + " file or directory%n", path); >catch (DirectoryNotEmptyException x) < System.err.format("%s not empty%n", path); >catch (IOException x) < System.err.println(x); >> > 

Источник

Оцените статью