In this article, we will be learning about the different ways in which you can read a text file in Java.
- Using FileReader.read
- Using BufferedReader
- Using Scanner
- Using RandomAccessFile
- Using Files.readString
- Using Files.readAllLines
- Using Files.Lines
Using FileReader.read
Java has an in-built class called java.io.FileReader. It represents a character stream, that is it can be used to read characters from an input file. It has a method called read which returns the next character from the file being read if present, or -1 if there are no more characters to be read.
Sample Code
FileReader fileReader = new FileReader("C:/readfile/input.txt"); System.out.println("Printing file contents:"); int c; while ((c = fileReader.read()) != -1) { System.out.print((char)c); } fileReader.close();
- Line 1 creates a FileReader object called fileReader corresponding to the input file
- Line 4 specifies a while loop that invokes the read method to read each character from the file. The read method returns a value of type int, this is then explicitly cast to char and printed to the console. The loop is repeated until the read method returns -1 after which the loop is terminated.
Using BufferedReader
The FileReader class seen above has one limitation. It performs an IO operation each time the read method is invoked. So, it is not very performance efficient. Java has another class called java.io.BufferedReader which overcomes this limitation. BufferedReader has an internal buffer which is a character array. When a read operation is performed on the BufferedReader the first time, it reads a large chunk of data into the internal buffer. Each subsequent read operation reads form this buffer. Thus, this reduces the number of IO operations and improves the performance. In addition, the BufferedReader has a convenience method called readLine which can be used to read a line of text. This returns the next line from the file if present or null if no more lines are present. The BufferedReader class cannot be used by itself, it is used in conjunction with a FileReader.
Sample Code
FileReader fileReader = new FileReader("C:/readfile/input.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); String line = null; System.out.println("Printing file contents:"); while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); fileReader.close();
- Line 1 creates a FileReader object called fileReader corresponding to the input file
- Line 2 creates a BufferedReader called bufferedReader corresponding to fileReader. By default, this creates a BufferedReader with an internal buffer that is capable of storing 8192 characters. However, this buffer size can also be changed programmatically.
- Line 4 specifies a while loop that invokes the readLine method to read each line from the file. This method reads data from the internal buffer and not the actual file. The loop is repeated until the readLine method returns null after which the loop is terminated.
Using Scanner
Java provides a class called java.util.Scanner. Though this is typically used to read input entered by a user on the command line, it can also be used to read the contents of a file. It has a method called hasNextLine which returns a boolean value if there is more data to be read. It also has a method called readLine which can be used to read the next line. As with BufferedReader, Scanner cannot be used by itself and needs to be used in conjunction with a FileReader.
Sample Code
FileReader fileReader = new FileReader("C:/readfile/input.txt"); Scanner sc = new Scanner(fileReader); System.out.println("Printing file contents:"); while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } fileReader.close(); sc.close();
- Line 1 creates a FileReader object called fileReader corresponding to the input file
- Line 2 creates a Scanner called sc corresponding to fileReader.
- Line 4 specifies a while loop. It invokes the hasNextLine method to checks if there is a line to be read and if so reads it via the nextLine method. The loop is repeated until the hasNextLine method returns false after which the loop is terminated.
Using RandomAccessFile
Java has an in-built class called RandomAccessFile. It allows reading/writing to a File. Not only that, it allows opening the file in read-only mode. This prevents the code from accidentally writing to the file. The RandomAccessFile has a method called readLine which can be used to read a line of text. This returns the next line from the file is present or null if no more lines are present.
Sample Code
RandomAccessFile randomAccessFile = new RandomAccessFile("C:/readfile/input.txt","rw"); String line = null; System.out.println("Printing file contents:"); while ((line = randomAccessFile.readLine()) != null) { System.out.println(line); }
- Line 1 creates a RandomAccessFile. In addition to the file path, it also specifies the mode in which the file is to be opened. In this case, “rw” is specified which means the file is opened in read-write mode. However, the file can be opened in read-only mode by specifying “r”.
- Line 4 specifies a while loop that invokes the readLine method to reads each line from the file. The loop is repeated until the readLine method returns null after which the loop is terminated.
Using Files.readString
Java has an in-built class called java.nio.Files. It has a lot of utility methods that can be used to perform operations on files. It also has some methods for reading a file.
It has a method called readString. It can be used to read the contents of a File into a String. It accepts as a parameter a Path object corresponding to the input file and returns a String with the contents of the file. Path is also a class in java.nio package which represents the path of a file on the file system.
Sample Code
Path path = Paths.get("C:/readfile/input.txt"); String str = Files.readString(path); System.out.println(str);
- Line 1 creates a Path object called path corresponding to the input file.
- Line 2 invokes the Files.readString method and assigns the result to str. This method is not recommended if the file being read is a large file. In this case, it can cause the code to run out of memory and cause a OutOfMemory error.
Using Files.readAllLines
The Files class also has a method called readAllLines. It can be used to read the contents of a File into a String List. It also accepts as a parameter a Path object corresponding to the input file and returns a String List.
Sample Code
Path path = Paths.get("C:/readfile/input.txt"); List<String> strList = Files.readAllLines(path); strList.forEach(str -&gt; System.out.println(str));
- Line 1 creates a Path object called path corresponding to the input file
- Line 2 invokes the Files.readAllLines method and assigns the result to strList.
Using Files.Lines
The Files class has a method called lines. It can be used to read the contents of a File into a String Stream. It also accepts as a parameter a Path object corresponding to the input file and returns a String List.
Sample Code
Path path = Paths.get("C:/readfile/input.txt"); Stream<String> stream = Files.lines(path); stream.forEach(str -> System.out.println(str));
- Line 1 creates a Path object called path corresponding to the input file
- Line 2 invokes the Files.lines method and assigns the result to stream.
Conclusion
So, in this article, we saw the various ways in which you can read a file in Java. We first saw how to read a file using a FileReader, BufferedReader, and Scanner. We then took a look at the Files class and the methods in the Files class like readString, readAllLines, and lines which can also be used to read a file.