-->

Java - Files

1. What is File Handling?

File handling in Java refers to performing operations on files, such as creating, reading, writing, and deleting them. Java provides several classes in the java.io and java.nio.file packages to handle these operations.

File handling is crucial for applications that need to store and retrieve data persistently, such as reading configuration files, logging information, or managing large datasets.

2. Java File Handling Classes

Key Classes for File Handling:

File: Represents a file or directory path.

FileWriter: Used to write character data to a file.

FileReader: Used to read character data from a file.

BufferedReader and BufferedWriter: Provide efficient reading and writing using buffers.

Scanner: Reads data from various input sources, including files.

Files (from java.nio.file): Provides utility methods for file manipulation.

3. Creating a New File

To create a new file, you can use the File class. The createNewFile() method creates a file if it doesn't exist and returns true; otherwise, it returns false.

Example: Creating a New File

import java.io.File;

import java.io.IOException;

public class CreateFile {

    public static void main(String[] args) {

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

        try {

            if (file.createNewFile()) {

                System.out.println("File created: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

4. Writing to a File

You can use FileWriter to write data to a file. It's advisable to use BufferedWriter for better performance.

Example: Writing to a File

import java.io.FileWriter;

import java.io.IOException;

public class WriteToFile {

    public static void main(String[] args) {

        try (FileWriter writer = new FileWriter("example.txt")) {

            writer.write("Hello, World!\nWelcome to Java File Handling.");

            System.out.println("Successfully wrote to the file.");

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

5. Reading from a File

To read data from a file, you can use classes like FileReader and BufferedReader, or the Scanner class for a simpler approach.

Example: Reading a File using BufferedReader

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ReadFromFile {

    public static void main(String[] args) {

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

            String line;

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

                System.out.println(line);

            }

        } catch (IOException e) {

            System.out.println("An error occurred.");

            e.printStackTrace();

        }

    }

}

Example: Reading a File using Scanner

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class ReadWithScanner {

    public static void main(String[] args) {

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

            while (scanner.hasNextLine()) {

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

            }

        } catch (FileNotFoundException e) {

            System.out.println("File not found.");

        }

    }

}

6. Deleting a File

To delete a file, you can use the delete() method of the File class.

Example: Deleting a File

import java.io.File;

public class DeleteFile {

    public static void main(String[] args) {

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

        if (file.delete()) {

            System.out.println("File deleted: " + file.getName());

        } else {

            System.out.println("Failed to delete the file.");

        }

    }

}

7. File Metadata (File Attributes)

You can access various file attributes like name, path, size, and more using methods from the File class.

Example: Getting File Information

import java.io.File;

public class FileInfo {

    public static void main(String[] args) {

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

        if (file.exists()) {

            System.out.println("File name: " + file.getName());

            System.out.println("Absolute path: " + file.getAbsolutePath());

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

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

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

        } else {

            System.out.println("The file does not exist.");

        }

    }

}

8. Working with Directories

Java also allows you to work with directories using the File class.

Example: Creating a Directory

import java.io.File;

public class CreateDirectory {

    public static void main(String[] args) {

        File dir = new File("MyDirectory");

        if (dir.mkdir()) {

            System.out.println("Directory created: " + dir.getName());

        } else {

            System.out.println("Directory already exists.");

        }

    }

}

Example: Listing Files in a Directory

import java.io.File;

public class ListFiles {

    public static void main(String[] args) {

        File folder = new File(".");

        File[] files = folder.listFiles();

        for (File file : files) {

            if (file.isFile()) {

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

            } else if (file.isDirectory()) {

                System.out.println("Directory: " + file.getName());

            }

        }

    }

}

9. Exception Handling in File I/O

When working with files, it's important to handle exceptions properly. Common exceptions include:

FileNotFoundException: The file you are trying to access does not exist.

IOException: An error occurs while performing input/output operations.

SecurityException: Your application does not have permission to access the file.

Best Practices:

Always close file resources using try-with-resources or finally blocks.

Handle specific exceptions to provide meaningful error messages.

10. Conclusion

Java's file handling capabilities are powerful and versatile, allowing you to work with files and directories efficiently. By using classes like File, FileWriter, BufferedReader, and Scanner, you can perform various file operations with ease.