Java MCQ: Which method is used to create a file in Java?
Answer:
Explanation:
The createNewFile()
method in Java is used to create a new file. It is a method of the File
class, which is part of the java.io
package. When you call createNewFile()
, it returns true
if the file was created successfully, or false
if the file already exists. This method throws an IOException
if an I/O error occurs.
Here’s an example of how to use createNewFile()
:
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
File file = new File("example.txt");
try {
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();
}
}
}
In this example, createNewFile()
attempts to create a file named example.txt
. If the file does not exist, it will be created, and a success message will be printed. If the file already exists, a message indicating this will be printed instead.
This method is essential for file handling in Java, particularly when you need to ensure that a file is created before writing to it.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html