File Handling in Java: Reading and Writing Files

 File handling is a crucial skill in Java programming that allows you to work with files and directories on your system. Learn how to read and write files effectively.


Java File Class:


The File class represents file and directory pathnames:


import java.io.File;


File file = new File("example.txt");


Checking File Properties:


if (file.exists()) {

    System.out.println("File size: " + file.length());

    System.out.println("Can read: " + file.canRead());

    System.out.println("Can write: " + file.canWrite());

    System.out.println("Is directory: " + file.isDirectory());

}


Reading Files:


Using FileReader and BufferedReader:


try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {

    String line;

    while ((line = reader.readLine()) != null) {

        System.out.println(line);

    }

} catch (IOException e) {

    e.printStackTrace();

}


Using Scanner:


try (Scanner scanner = new Scanner(new File("data.txt"))) {

    while (scanner.hasNextLine()) {

        System.out.println(scanner.nextLine());

    }

} catch (FileNotFoundException e) {

    e.printStackTrace();

}


Writing to Files:


Using FileWriter and BufferedWriter:


try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {

    writer.write("Hello, World!");

    writer.newLine();

    writer.write("This is a new line");

} catch (IOException e) {

    e.printStackTrace();

}


Appending to Files:


try (FileWriter fw = new FileWriter("data.txt", true)) {

    fw.write("Appended text\n");

} catch (IOException e) {

    e.printStackTrace();

}


Creating and Deleting Files:


File file = new File("newfile.txt");


// Create file

if (file.createNewFile()) {

    System.out.println("File created");

}


// Delete file

if (file.delete()) {

    System.out.println("File deleted");

}


Working with Directories:


File dir = new File("myFolder");


// Create directory

if (dir.mkdir()) {

    System.out.println("Directory created");

}


// List files in directory

String[] files = dir.list();

for (String filename : files) {

    System.out.println(filename);

}


Binary Files:


For reading/writing binary data:


try (FileInputStream fis = new FileInputStream("data.bin");

     FileOutputStream fos = new FileOutputStream("copy.bin")) {

    

    int b;

    while ((b = fis.read()) != -1) {

        fos.write(b);

    }

} catch (IOException e) {

    e.printStackTrace();

}


Try-with-Resources:


Always use try-with-resources to automatically close files:


try (FileReader fr = new FileReader("file.txt")) {

    // Read file

} // File automatically closed


Best Practices:


- Always close files after use

- Use try-with-resources for automatic closure

- Handle IOExceptions appropriately

- Check if file exists before operations

- Use absolute paths when possible

- Be careful with file permissions


Common Exceptions:


- FileNotFoundException: File doesn't exist

- IOException: General I/O errors

- SecurityException: No permission to access file


Mastering file handling enables your Java programs to persist data and work with external resources!

Comments

Popular posts from this blog

Getting Started with Java Programming: A Beginner's Guide

Career Transitions in Tech: From Student to Professional

Smart Money Management for Students: Budgeting Basics