In this example you’ll learn how to create and delete a file. Using the new Files
class helper from the JDK 7 you can create a file using the Files.createFile(Path)
method. To delete a file you can use the Files.delete(Path)
method.
Before create a file and delete a file we can check to see if the file exists or not using the Files.exists(Path)
method. In the code snippet below we’ll create a file when the file is not exist. And we’ll delete the file if the file exists.
package org.kodejava.io;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateDeleteFile {
public static void main(String[] args) {
try {
// Create a config.cfg file under D:Temp directory.
Path path = Paths.get("F:/Temp/config.cfg");
if (!Files.exists(path)) {
Files.createFile(path);
}
// Delete the path.cfg file specified by the Path.
if (Files.exists(path)) {
Files.delete(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024