CodeToLive

File Handling in Java

File handling in Java allows you to read from and write to files. Java provides classes like File, FileReader, FileWriter, BufferedReader, BufferedWriter, and FileInputStream and FileOutputStream for binary file handling.

Reading from a Text File

Use FileReader and BufferedReader to read from a text file.


import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
      

Writing to a Text File

Use FileWriter and BufferedWriter to write to a text file.


import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {
            bw.write("Hello, World!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
      

Reading from a Binary File

Use FileInputStream to read from a binary file.


import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.bin")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
      

Writing to a Binary File

Use FileOutputStream to write to a binary file.


import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("example.bin")) {
            String text = "Hello, Binary World!";
            fos.write(text.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
      

Appending to a File

To append data to an existing file, use the FileWriter constructor with the true flag.


import java.io.*;

public class Main {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt", true))) {
            bw.write("\nAppending a new line.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
      

Deleting a File

Use the File class to delete a file.


import java.io.*;

public class Main {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.delete()) {
            System.out.println("File deleted successfully.");
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}
      
Next: Exception Handling