In Java, file creation is accomplished using the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that this method is enclosed within a try…catch block, as it throws an IOException if an error occurs (such as if the file cannot be created for some reason).
import public |
The output expected is:
|
To create a file within a particular directory (which requires permission), specify the file’s path. Use double backslashes to escape the “\” character on Windows. On Mac and Linux systems, you can directly specify the path, such as: /Users/name/filename.txt.
File myObj = new File(“C:\\Users\\MyName\\filename.txt”); |
In the subsequent example, we utilize the FileWriter class along with its write() method to write text to the file created in the previous example. It’s essential to remember that once writing to the file is complete, you should close it using the close() method.
import public |
The expected output is:
|