Java : How to work with file and directory
The
By using the static
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Post a Comment