Reading and Writing Text File

Reading and writing text files in Java can be achieved using BufferedReader and BufferedWriter for efficient text operations, as well as Scanner for convenient input processing. Below are detailed explanations and examples for each method:

1. Reading Text Files Using BufferedReader:

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

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

In this example, BufferedReader is used to read text data line by line from the "input.txt" file. The readLine() method reads a line of text. The try-with-resources statement ensures that each resource is closed at the end of the statement.

2. Writing Text Files Using BufferedWriter:

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

public class WriteTextFileWithBufferedWriter {
    public static void main(String[] args) {
        String content = "Hello, Text File!";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            bw.write(content);
            System.out.println("Data written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, BufferedWriter is used to write text data to the "output.txt" file. The write(String) method writes a string to the output stream.

3. Reading Text Files Using Scanner:

javaCopy codeimport java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadTextFileWithScanner {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("input.txt"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, Scanner is used to read text data line by line from the "input.txt" file. The hasNextLine() method checks if there is another line in the file, and nextLine() method reads the next line.

4. Writing Text Files Using BufferedWriter and User Input (Scanner):

javaCopy codeimport java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class WriteTextFileWithScanner {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("Enter text (type 'exit' to stop):");
            String input;
            while (!(input = scanner.nextLine()).equals("exit")) {
                bw.write(input + "\n");
            }

            System.out.println("Data written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, Scanner is used to read user input from the console, and the input is written to the "output.txt" file using BufferedWriter. The program continues to take input until the user types "exit".

Explanation:

  • Using BufferedReader and BufferedWriter:

    • BufferedReader is used for efficient reading of text from a character-input stream, such as a file.

    • BufferedWriter is used for efficient writing of text to a character-output stream, such as a file.

  • Using Scanner:

    • Scanner is a versatile class that can be used to read user input from the console or text from a file.

Remember to handle exceptions properly to ensure your file operations are robust and can handle any potential issues that may arise during reading and writing.

Last updated