Create
Lesson 6 of 11 in Coddy's File Handling in Java course.
To create a file in Java, use the File class constructor with the desired file name and then execute the method createNewFile(). The method will return true if the file was created successfully, or false if the file already exists:
try {
File file = new File("data.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}The above code creates the file named “data.txt”, note that you must handle the IOException exception.
Challenge
EasyCreate a function named createFile that gets a filename and creates it.
If the file already exists, output:
File already exists.Otherwise:
File created successfully!Try it yourself
import java.io.File;
import java.io.IOException;
class CreateFile {
public static void createFile(String filename) {
// Write code here
}
}