DEV Community

PONVEL M
PONVEL M

Posted on

File Handling in Java (Complete Guide for Beginners)

File handling in Java is used to create, read, write, update, and delete files.
It is very important for building real-world applications like logging systems, data storage, reports, etc.

What is File Handling?

File handling means working with files stored on your computer.
Java provides built-in classes in the java.io package for this.

Important Classes in Java File Handling

Class Purpose
File Create & manage files
FileWriter Write data to file
FileReader Read data from file
BufferedWriter Efficient writing
BufferedReader Efficient reading
PrintWriter Formatted writing
Scanner Read file easily

1. Creating a File

import java.io.File;
import java.io.IOException;

class Main {
    public static void main(String[] args) {
        try {
            File file = new File("test.txt");

            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists");
            }

        } catch (IOException e) {
            System.out.println("Error occurred");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Writing to a File

Using FileWriter

import java.io.FileWriter;
import java.io.IOException;

class Main {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("test.txt");
            writer.write("Hello, this is Java File Handling!");
            writer.close();

            System.out.println("Data written successfully");

        } catch (IOException e) {
            System.out.println("Error writing file");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Using BufferedWriter (Faster)

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

class Main {
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));

        bw.write("Buffered writing example");
        bw.newLine();
        bw.write("Second line");

        bw.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Using PrintWriter (Formatted Output)

import java.io.PrintWriter;

class Main {
    public static void main(String[] args) throws Exception {
        PrintWriter pw = new PrintWriter("test.txt");

        pw.println("Name: Ponvel");
        pw.println("Score: 95");

        pw.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Reading from a File

Using FileReader

import java.io.FileReader;

class Main {
    public static void main(String[] args) throws Exception {
        FileReader fr = new FileReader("test.txt");
        int i;

        while ((i = fr.read()) != -1) {
            System.out.print((char)i);
        }

        fr.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Using BufferedReader (Efficient)

import java.io.BufferedReader;
import java.io.FileReader;

class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        String line;

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Using Scanner (Simple Way)

import java.io.File;
import java.util.Scanner;

class Main {
    public static void main(String[] args) throws Exception {
        File file = new File("test.txt");
        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {
            System.out.println(sc.nextLine());
        }

        sc.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Deleting a File

import java.io.File;

class Main {
    public static void main(String[] args) {
        File file = new File("test.txt");

        if (file.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Failed to delete file");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

5. File Methods (Must Know)

Method Description
createNewFile() Creates a new file
exists() Checks file exists
delete() Deletes file
getName() Returns file name
getAbsolutePath() Returns full path
length() Returns file size
canRead() Check read permission
canWrite() Check write permission

Example

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

System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
System.out.println(file.length());
System.out.println(file.canRead());
Enter fullscreen mode Exit fullscreen mode

Exception Handling in File Handling

File operations may throw errors (IOException)

try {
    // file code
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}
Enter fullscreen mode Exit fullscreen mode

Advantages of File Handling

✔ Store data permanently
✔ Useful for logs & reports
✔ Helps in real applications

Disadvantages

Slower than memory
Requires exception handling

Conclusion

File handling is a must-know concept in Java for real-world development.

Create files
Read & write data
Manage file operations

Top comments (0)