We need to use Java File handling class from java.io package.
import java.io.File;
Using the above file class we will create one object.
File my_file_obj = new File("my_new_file.txt");
Here my_new_file.txt is the name of the file.
To handle the exceptions we will include the pacakge IOException.
createNewFile()
We will be using createNewFile() method of File class to create new file. This method returns true or false based on the successful creation of file.
Here is the code to create a new file.
package Pack1;
import java.io.File;
import java.io.IOException;
public class my_file {
public static void main(String[] args) {
try {
File my_file_obj = new File("my_new_file.txt"); // file object
if (my_file_obj.createNewFile()) {
System.out.println("New File created: ");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("OOps some error.");
e.printStackTrace();
}
}
}
We used my_file_obj as file object and createNewFile() method to create new file. In above code we have included try.. catch to get the exceptions in our file creating process.
Location of the new file.
In above code the file is created in the current or project directory. This depends on setting and project you are using in your system. Here is one sample path of default file creation