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 is exist 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 is exist.
package org.kodejava.example.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("D:/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 install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020