- How to delete all java files
- Java — How to Delete Files and Folders?
- 1. Overview
- 2. Java Files Delete Example
- 3. Java Delete Folder Example
- 4. Conclusion
- Labels:
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
- How to delete a directory recursively in Java
- You might also like.
How to delete all java files
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
Java — How to Delete Files and Folders?
A quick guide to delete the files and folders in java with example programs.
1. Overview
In this tutorial, We will learn how to delete the files and folders in java.
Let us learn the example programs on file deletion and folder removal in java.
2. Java Files Delete Example
First, Use delete() method on the file object to delete the file. Returns true if the file is delete successfully and else return false if there are any failures.
In the below program, we have taken two files test.log file is present in the location and no-file.log does not exists on the location.
Let us see the behaviour of delete() method.
package com.javaprogramto.files.delete; import java.io.File; /** * How to delete the file in java using File api delete() method. * * @author JavaProgramTo.com * */ public class FileDelete < public static void main(String[] args) < // File deletion success String fileName = "src/main/java/com/javaprogramto/files/delete/test.log"; File file = new File(fileName); boolean isFileDeleted = file.delete(); if(isFileDeleted) < System.out.println("File deleted without any errors for "+fileName); >else < System.out.println("File deletion is failed"); >// File deletion error. fileName = "src/main/java/com/javaprogramto/files/delete/no-file.log"; file = new File(fileName); isFileDeleted = file.delete(); if(isFileDeleted) < System.out.println("File deleted without any errors for "+fileName); >else < System.out.println("File deletion is failed for "+fileName); >> >
File deleted without any errors for src/main/java/com/javaprogramto/files/delete/test.log File deletion is failed for src/main/java/com/javaprogramto/files/delete/no-file.log
3. Java Delete Folder Example
Next, we will try to delete the folder which is having the files and next empty folder deletion using delete() method.
package com.javaprogramto.files.delete; import java.io.File; /** * How to delete the folder in java using File API delete() method. * * @author JavaProgramTo.com * */ public class FileDeleteFolder < public static void main(String[] args) < // Folder deletion not done String folderName = "src/main/java/com/javaprogramto/files/delete"; File file = new File(folderName); boolean isFileDeleted = file.delete(); if(isFileDeleted) < System.out.println("Folder with files is deleted"); >else < System.out.println("Folder with files is not deleted"); >// Empty Folder deletion success . folderName = "src/main/java/com/javaprogramto/files/emptyfolder"; file = new File(folderName); isFileDeleted = file.delete(); if(isFileDeleted) < System.out.println("Empty Folder deleted "); >else < System.out.println("Empty Folder deletion is failed for "+folderName); >> >
Folder with files is not deleted Empty Folder deleted
Note: if the folder is empty then only folder will be deleted and folder which has files won’t be deleted. But, we can delete the files folder after deleting all files.
4. Conclusion
In this article, we’ve seen how to delete the files and folder in java with examples.
Labels:
SHARE:
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content
How to delete a directory recursively in Java
In an earlier article, we looked at different ways of deleting a directory in Java. In this article, you’ll learn how to delete a non-empty directory recursively — delete all its files and sub-folders.
Java provides multiple methods to delete a directory. However, the directory must be emptied before we delete it. To remove all contents of a particular directory programmatically, we need to use recursion as explained below:
- List all contents (files & sub-folders) of the directory to be deleted.
- Delete all regular files of the current directory (exist from recursion).
- For each sub-folder of the current directory, go back to step 1 (recursive step).
- Delete the directory.
Let us look at different ways to implement the above simple recursive algorithm.
In Java 8 or higher, you can use Files.walk() from NIO API (classes in java.nio.* package) to recursively delete a non-empty directory. This method returns a Stream that can be used to delete all files and sub-folders as shown below:
try // create a stream StreamPath> files = Files.walk(Paths.get("dir")); // delete directory including files and sub-folders files.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::deleteOnExit); // close the stream files.close(); > catch (IOException ex) ex.printStackTrace(); >
In the above example, Files.walk() returns a Stream of Path . We sorted it in the reverse order to place the paths indicating the contents of directories before directories itself. Afterward, it maps Path to File and deletes each File .
To delete a non-empty directory using Java legacy I/O API, we need to manually write a recursive function to implement the above algorithm. Here is how it looks like:
public void deleteDir(File dir) File[] files = dir.listFiles(); if(files != null) for (final File file : files) deleteDir(file); > > dir.delete(); >
As you can see above, we are using File.listFiles() method to list all files and sub-directories in the directory. For each file, we recursively call deleteDir() method. In the end, we delete the directory using File.delete() . Now you can call the above method as follows:
File dir = new File("dir"); deleteDir(dir);
The Apache Commons IO library provides FileUtils.deleteDirectory() method to delete a directory recursively including all files and sub-directories:
try // directory path File dir = new File("dir"); // delete directory recursively FileUtils.deleteDirectory(dir); > catch (IOException ex) ex.printStackTrace(); >
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>2.6version> dependency>
implementation 'commons-io:commons-io:2.6'
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.