Reading a plain text file in Java

To read a plain text file in Java, you can use the following code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    try {
      // Open the file
      BufferedReader reader = new BufferedReader(new FileReader("filename.txt"));

      // Read the file line by line
      String line = reader.readLine();
      while (line != null) {
        System.out.println(line);
        line = reader.readLine();
      }

      // Close the file
      reader.close();
    } catch (IOException e) {
      // Handle the exception
    }
  }
}

This code opens the file "filename.txt" and reads it line by line. Each line is printed to the console until the end of the file is reached.

Note that this code assumes that the file is located in the same directory as the Java program. If the file is located elsewhere, you will need to specify the full path to the file.

You will also need to import the following classes:

  • java.io.BufferedReader: This class provides a buffered reader that can be used to read text from a character-input stream.
  • java.io.FileReader: This class is a subclass of InputStreamReader and is used to read characters from a file.
  • java.io.IOException: This class represents an input/output exception that can occur when reading from a file.