Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Essential Java Classes
  5. File I/O in Java

File I/O in Java

File I/O in Java allows programs to interact with files stored on the file system—reading, writing, creating, deleting, and checking properties of files or directories.

The File class represents the path to a file or directory—not the content. It allows you to:

  • Check if a file or directory exists
  • Create or delete files/directories
  • Rename files
  • Get file properties (like size, path, read/write permissions)

Common Methods:

file handling in java

Java provides two types of streams for reading:

a.) Byte-Oriented (Binary Files)

  • FileInputStream (for raw bytes like images, PDFs, etc.)

b.) Character-Oriented (Text Files)

  • FileReader → reads text files as characters
  • BufferedReader → wraps FileReader for efficient reading

Example: Reading a Text File Using BufferedReader:

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

public class ReadFromFile {
    public static void main(String[] args) {
        String fileName = "my_document.txt"; // Make sure this file exists

        // try-with-resources ensures the stream is closed automatically
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;

            while ((line = reader.readLine()) != null) {
                System.out.println(line); // Print each line of the file
            }

        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

a. Byte-Oriented:

  • FileOutputStream

b. Character-Oriented:

  • FileWriter → writes characters
  • BufferedWriter or PrintWriter → improves performance, adds methods like println()

Example (Reading from a file using BufferedReader):

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

public class WriteToFile {
    public static void main(String[] args) {
        String fileName = "output.txt";

        // try-with-resources ensures the writer is closed automatically
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write("Hello, Java File I/O!");
            writer.newLine();
            writer.write("This is a second line.");
            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
    }
}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *