File Handling in Java Understanding file operations with example programs
Introduction to File Handling • File handling allows programs to read/write data permanently. • It is part of java.io and java.nio packages. • Common classes used: - File - FileReader / FileWriter - BufferedReader / BufferedWriter - FileInputStream / FileOutputStream - Scanner
The File Class • The File class represents files or directories. • It provides methods to create, delete, and get file information. Example: File obj = new File("example.txt"); if(obj.exists()) { System.out.println("File exists"); } else { System.out.println("File not found"); }
Writing to a File Example import java.io.FileWriter; import java.io.IOException; public class WriteToFile { public static void main(String[] args) { try { FileWriter writer = new FileWriter("output.txt"); writer.write("Hello, File Handling in Java!"); writer.close(); System.out.println("Successfully written to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
Reading from a File Example import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFromFile { public static void main(String[] args) { try { File file = new File("output.txt"); Scanner reader = new Scanner(file); while (reader.hasNextLine()) { String data = reader.nextLine(); System.out.println(data); } reader.close(); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
Summary • File handling enables persistent data storage. • Key classes: File, FileWriter, FileReader, Scanner. • Always handle exceptions like IOException. • Close files after use to avoid resource leaks.