Java - File Handling
Java file handling refers to the process of working with files and directories in Java. It allows you to create, read, write, and delete files and directories on your computer or network. In Java, you can perform file handling using the java.io package.
Here are the basic steps for file handling in Java:
Creating a File Object: To work with a file, you need to create a File object, which represents the file on disk.
Example: File file = new File("C:/Users/User/Desktop/myfile.txt");
Creating a Directory: To create a directory, you can use the mkdir() method of the File class.
File dir = new File("C:/Users/User/Desktop/mydir");
dir.mkdir();
Reading Data from a File: To read data from a file, you can use the FileReader and BufferedReader classes.
FileReader fr = new FileReader("C:/Users/User/Desktop/myfile.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
fr.close();
Writing Data to a File: To write data to a file, you can use the FileWriter and BufferedWriter classes.
FileWriter fw = new FileWriter("C:/Users/User/Desktop/myfile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Hello, World!");
bw.newLine();
bw.write("How are you?");
bw.close();
Deleting a File: To delete a file, you can use the delete() method of the File class.
File file = new File("C:/Users/User/Desktop/myfile.txt");
file.delete();
Deleting a Directory: To delete a directory, you can use the delete() method of the File class.
Example: File dir = new File("C:/Users/User/Desktop/mydir");
dir.delete();
Note: Before deleting a directory, you need to make sure that it is empty. If it contains any files or sub-directories, you need to delete them first.