This example demonstrates how to create and delete files using the Apache commons library.
Maven Dependency
Let's add maven dependency before creating these examples:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
Apache FileUtils create and delete files
The example creates a new file, checks for its existence, deletes it, and checks for its existence again.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class CreateDeleteFileEx {
public static void main(String[] args) throws IOException {
File myfile = new File("src/main/resources/myfile.txt");
FileUtils.touch(myfile);
if (myfile.exists()) {
System.out.println("The file exists");
} else {
System.out.println("The file does not exist");
}
FileUtils.deleteQuietly(myfile);
if (myfile.exists()) {
System.out.println("The file exists");
} else {
System.out.println("The file does not exist");
}
}
}
A new file is created with FileUtils.touch() and deleted with FileUtils.deleteQuietly().
Comments
Post a Comment