Java : How to work with file and directory

The java.nio.file package (from Java 7) has improved the way we work with the file system.

Create a directory

For creating a new directory, we get a Path object for the provided path. Then, we check if the directory exists. If not, we call the static createDirectories() method of the Files class.

String myDirectory = "c:/remy/files";
Path directory = Paths.get(myDirectory);
if(Files.notExists(directory))
Files.createDirectories(directory);

Create a File


For creating a file, we follow basically the same process. But we get a Path object that refers to the directory and file. If the file doesn't exist, we call createFile() method of the Files class.

String myFile = "company.json";
Path pathToMyFile = Paths.get(myDirectory,myFile);
if(Files.notExists(pathToMyFile))
Files.createFile(pathToMyFile);

Iterate through Files in a directory


By using the static newDirectoryStream() method of the Files class, you can list the files in a directory this way:

if(Files.exists(myDirectory) && Files.isDirectory(myDirectory)){
DirectoryStream<Path> stream = Files.newDirectoryStream(myDirectory);
stream.forEach(path -> {
if(Files.isRegularFile(path))
System.out.println(path.getFileName());
});
}



Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form