How do I create and delete a file in JDK 7?

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();
        }
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.