Creating and Writing to a File
Once we are familiar with how to list the contents of directories, the next logical step is to proceed with the creation of files and folders. Let's start by creating and writing data into a file by using java.nio
. The easiest way to create a file using this API requires calling the following:
Files.createFile(newFilePath);
At the same time, creating a directory is as simple as this:
Files.createDirectories(newDirPath);
As a good practice, you should check whether directories and/or files exist prior to creating any with the same name. There is a simple method that will look into any objects of the Path class to see whether any can be found in the folder our program is exploring:
Files.exists(path);
Let's put all of this together into a single example that will create a folder, and then a file inside the folder:
Example06.java
1Â Â import java.io.IOException; 2Â Â import java.nio.file.Files; 3Â Â ...