File Reader/Writer in Java

Below is an example of how you can use Java's FileReader and FileWriter classes to read from and write to a file.

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

public class FileReadWriteExample {

    public static void main(String[] args) {
        // Replace "input.txt" and "output.txt" with your file names
        String inputFile = "input.txt";
        String outputFile = "output.txt";

        // Reading from a file using FileReader and BufferedReader
        try (FileReader fileReader = new FileReader(inputFile);
                BufferedReader bufferedReader = new BufferedReader(fileReader)) {

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println("Read from file: " + line);

                // You can process the line as needed here

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

        // Writing to a file using FileWriter and BufferedWriter
        try (FileWriter fileWriter = new FileWriter(outputFile);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {

            // Replace the following line with the content you want to write
            String contentToWrite = "Hello, this is written to the file!";
            bufferedWriter.write(contentToWrite);

            System.out.println("Write to file: " + contentToWrite);

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