Create New File
File Handling In Java
We need to create a new file, write content to the file, delete content from the file and also delete the file. File handling is a useful part of any application. You can import java.io.File;
to create a new file.
Info
Note: With the help of file management in java, we can automatically create, read, update, and delete a file. All the files are stored in a local file system.
Create New File
import java.io.File; // For File Work Import the File class
public class Main{
public static void main(String[] args) {
try {
File f = new File("myfile.txt");
if (f.createNewFile()) {
System.out.println("File is successfully created " + f.getName());
} else {
System.out.println("Seems like file already exist.");
}
} catch (Exception e) {
System.out.println("An error occurred. "+e.getMessage());
}
}
}
- We are creating an object of class File, i.e., f.
- The f.createNewFile() is responsible to create new file.
Don't forget to add try-catch while creating a new file.
Create New File In Specific Directory
import java.io.File; // For File Work Import the File class
public class Main{
public static void main(String[] args) {
try {
File f = new File("C://hello/myfile.txt");
if (f.createNewFile()) {
System.out.println("File is successfully " + f.getName());
} else {
System.out.println("Seems like file already exist.");
}
} catch (Exception e) {
System.out.println("An error occurred. "+e.getMessage());
}
}
}
Info
Note: Make sure that you have permission while creating a file.