Delete files and directories in java

Java Program to Delete Files and Directories

To delete files or directory using Java, delete() and deleteOnExit() methods are given in the java.io.File class. Using these methods we can also delete the directory with all files. First, let us demonstrate the method and then develop the program to delete all files in a directory.

delete() method

The delete() method returns true if and only if the file or directory is successfully deleted, else it returns false. If the given pathname represents a directory not a file then in order to delete them directory must be empty.

The delete() method can throw IOException if the file can’t be deleted. It is useful for error reporting and to diagnose why a file cannot be deleted. It can also throw SecurityException if there is a security manager that exists and it denies delete access to the file.

deleteOnExit() method

The deleteOnExit() method requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Files (or directories) are deleted in the reverse order that they are registered. Invoking this method to delete a file or directory that is already registered for deletion has no effect. Deletion will be attempted only for normal termination of the virtual machine.

Читайте также:  What is margin and padding in css

Once deletion has been requested through deleteOnExit() method then it is not possible to cancel the request. This method should therefore be used with care. This method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead. It also throws SecurityException if there is a security manager exists and it denies delete access to the file.

File-level locking:- File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it in a specific time and to prevent reading of the file while it’s being modified or deleted. For example:- open any file and try to delete from the file, we can’t do it because the file is locked.

Note:- Both methods delete files/directories permanently.

Java program to delete files if exists

Previously we have written different programs to create folder, you can use them or create file manually. See:- Create File in Java.

import java.io.File; import java.io.IOException; public class DeleteFile < public static void main(String[] args) < File f1 = new File("Hello.java"); File f2 = new File("Hello.class"); if(f1.exists())< f1.delete(); // delete immediately System.out.println(f1 + " deleted"); System.out.println("f1 exists: " + f1.exists()); >else < System.out.println(f1 + " doesn't exist"); >if(f2.exists()) < f2.deleteOnExit(); // delete after JVM termination System.out.println(f2 + " deletion requested on exit"); System.out.println("f2 exists: " + f2.exists()); >else < System.out.println(f2 + " doesn't exist"); >> >

Hello.java deleted
f1 exists: false
Hello.class deletion requested on exit
f2 exists: true

If we run the program for second time then file is not available, that’s why it displays,

Delete empty Folder

When the directory is non-empty then both delete() and deleteOnExit() method returns false and doesn’t delete the directory or folder. Therefore, we must check the directory is empty or not.

In current working directory,

import java.io.File; public class DeleteDirectory < public static void main(String[] args) < File f1 = new File("dir1"); // File f1 = new File("dir2"); boolean flag = false; if(f1.exists())< flag = f1.delete(); if(flag)< System.out.println(f1 + " deleted"); >else < // check is it directory if(f1.isDirectory()) System.out.println(f1 + " is not empty"); >> else < System.out.println(f1 + " doesn't exist"); >> >

Now, let us try to delete dir2 which is not empty. In this case, the output is,

Java program to delete directory with files

A directory can contain multiple files and directory, those child directories can be empty or have multiple files and directory. So, we have to develop program in such a way that it checks each folder and files and then delete them.

Procedure,
1) Go to a directory
2) List all files and directories
3) If it is a file then delete them
4) If it is a directory then again start from step-1
5) if the directory is empty then delete the directory.

We need to use recursion technique to solve the problem. In recursion technique, we define a method who call itself within a certain condition.

// method to delete files and folders recusively public void directoryDelete(File dir) throws Exception < if(dir != null) < File dirList[] = dir.listFiles(); if(dirList != null) < for(File f : dirList) < if(f.isFile()) f.delete(); else directoryDelete(f); >> dir.delete(); > >

Current Working directory => TestFile directory (TestFile is inside current directory),

  • dir1
    • abc11.txt
    • dir11
      • abc111.txt
      • abc112.java
      • dir21
      • dir22
        • dir221
        • abc2211.pdf
        import java.io.File; class Test < public static void main(String[] args) < DeleteDirectory dir = new DeleteDirectory(); try < dir.directoryDelete("TestFile"); >catch(Exception e) < e.printStackTrace(); >> > class DeleteDirectory < public void directoryDelete(String file) throws Exception < directoryDelete(new File(file)); >public void directoryDelete(File dir) throws Exception < if(dir != null) < File dirList[] = dir.listFiles(); if(dirList != null) < for(File f : dirList) < if(f.isFile()) < f.delete(); // to see deletion order System.out.println(f + " file deleted"); >else < directoryDelete(f); >> > if(dir.delete()) < // to see deletion order System.out.println(dir + " directory deleted"); >else < if(!dir.exists()) System.out.println(dir + " not exist"); >> else < System.out.println("Directory is null"); >> >

        TestFile\dir1\abc11.txt file deleted
        TestFile\dir1\dir11\abc111.txt file deleted
        TestFile\dir1\dir11\abc112.java file deleted
        TestFile\dir1\dir11 directory deleted
        TestFile\dir1\dir12 directory deleted
        TestFile\dir1 directory deleted
        TestFile\dir2\dir21 directory deleted
        TestFile\dir2\dir22\abc2211.pdf file deleted
        TestFile\dir2\dir22\dir221 directory deleted
        TestFile\dir2\dir22 directory deleted
        TestFile\dir2\dir23 directory deleted
        TestFile\dir2 directory deleted
        TestFile directory deleted

        If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

        Источник

        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); >> > 

        Источник

        Deleting a File or Directory in Java

        Learn to delete a specified file or directory in Java. Note that different methods behave differently for deleting non-empty directories.

        1. Deleting with File Class

        To delete a file, File class provides the following methods:

        1.1. boolean delete()

        • It deletes the specified file or directory. In the case of a directory, the directory must be empty in order to be deleted.
        • This method returns true if and only if the file or directory is successfully deleted; false otherwise.
        • In case of any permission issues, SecurityException is thrown.
        • In the file cannot be deleted for any reason then it does not throw any exception, rather it simply returns false .

        1.2. void deleteOnExit()

        • It registers the file for deletion when the virtual machine terminates.
        • It is useful in the case of unit testing to delete temporary files after the test execution is finished.
        • Note that once deletion has been requested, it is not possible to cancel the request.
        • Deletion will be attempted only when the JVM terminates normally, otherwise, the behavior is unspecified.
        • If a file or directory is already for deletion then this method has no effect.
        //Deleting a file immidiately File file = new File("c:/temp/one.txt"); boolean deleted = file.delete(); //Registering for deletion File file = new File("c:/temp/two.txt"); file.deleteOnExit();

        2. Deleting with java.nio.file.Files

        The Files class also provides two following methods:

        • Similar to File.delete(), this method also deletes a file or an empty directory.
        • The difference is that this method throws IOException if the file cannot be deleted which is useful in debugging the reason for failure.
        • It throws NoSuchFileException if the specified file or directory does not exist.
        • Similarly, it throws DirectoryNotEmptyException if the specified directory is not empty.

        2.2. boolean deleteIfExists(path)

        • This method is a little different version of delete(). It does not throw NoSuchFileException if the file or directory is not present.
        • It deletes a file or directory if it exists.
        • This method returns true if the file was deleted by this method; false if the file could not be deleted.
        Path path = Path.of("c:/temp/one.txt"); Files.delete(path); //or Path path = Path.of("c:/temp/two.txt"); boolean success = Files.deleteIfExists(path);

        3. Deleting with Commons IO’s FileUtils

        The FileUtils class has following useful methods for deleting the files and directories:

        File delete(file) : deletes a file or directory. Internally it uses Files.delete() method.
        void deleteDirectory(file) : deletes a directory recursively. It returns IOException in case the deletion is unsuccessful.
        boolean deleteQuietly(file) : deletes a file without ever throwing an exception. If the file is a directory, delete it and all sub-directories. It does not require the directory to be empty as it is needed with other methods.

        FileUtils.delete(file); FileUtils.deleteQuietly(new File("c:/temp")); boolean success = FileUtils.deleteDirectory(new File("c:/temp"));

        Deleting a file or directory in Java is a very simple operation and mostly done in a single statement. Still, it may fail sometimes for two reasons i.e. permission issues and a non-empty directory.

        As a best practice, we can use Files.delete(path) for deleting a file and FileUtils.deleteDirectory() for deleting a directory recursively.

        Источник

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