This section demonstrates you how to create a new file.
Description of code:
Manipulating a file is a common task in programming. Java makes this easy by providing many useful tools. Through the use of these tools, you can can easily create a new empty file. Now for this task, we have used the method createNewFile() of boolean type which creates a new empty file if and only if a file with this name does not yet exist.
createNewFile(): This method of File class creates an empty file at the specified file location if a file with this name does not exist.
exists(): This method of File class checks whether the given file exists or not.
Here is the code:
import java.io.*;
public class FileCreate {
public static void main(String[] args) throws Exception {
File file = new File("C:/newfile.txt");
if (file.exists()) {
System.out.println("File already exists");
} else {
file.createNewFile();
System.out.println("File is created");
}
}
}
Through the method createNewFile(), you can create a file.
Output:
| File is created |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.