Reading from Files

When working with files in Java, reading the content is a fundamental operation. Java provides multiple methods to read both text and binary files.

  • Using FileReader and BufferedReader to Read Text Files
  • Using FileInputStream to Read Binary Files
  • Using Files.readAllLines() (NIO)
  • Using the Scanner Class to Read Files

Reading Text Files with FileReader and BufferedReader

For reading text files, the combination of FileReader and BufferedReader is frequently used. FileReader is designed to read files character by character, while BufferedReader improves performance by buffering the input, allowing us to read the file more efficiently.

  • FileReader is used to open and read the example.txt file.
  • BufferedReader is wrapped around FileReader to read the file line by line.
  • The readLine() method reads each line of the file until the end is reached.

Reading Binary Files with FileInputStream

If we need to read binary data, such as images or multimedia files, FileInputStream is the go-to option. This class reads raw byte data, making it suitable for non-text files.

  • FileInputStream opens and reads the file example.bin byte by byte.
  • The read() method returns a byte of data or -1 when the end of the file is reached.

Reading Files with Files.readAllLines()

Introduced in Java 7, NIO (New I/O) provides modern utilities for working with files. The Files.readAllLines() method allows us to read the entire content of a text file into a List<String>. This is particularly useful when we want to load all lines at once into memory.

  • Files.readAllLines() reads all the lines of example.txt into a List<String>.
  • This method is convenient for smaller files, but might not be efficient for very large files since it loads the entire file into memory.

Reading Files with the Scanner Class

The Scanner class is versatile and can be used to read data from a variety of sources, including files. It’s especially helpful when we need to parse data or break it down into tokens.

  • Scanner reads the file example.txt line by line.
  • It’s easy to use when you want to read data and process or tokenize it on the fly.