Construction. Reading Files
[comp1110-96]
Construction. Reading Files
[comp1110-96]Interacting with files is risky business, much more so than all the other things we have done in the course so far. This is because they are shared with other programs and users that might work with them at the same time we do. Files might exist one moment and then not anymore, without our program having done anything, just because some other program deleted it. They might exist but cannot be opened, because the user running our program does not have permission to read it, or because there is some deeper problem with the file system.
For that reason, Java specifies a number of checked exceptions that you need to deal with when opening files and reading, usually under the umbrella of IOException.
In principle, when opening a file, you can have access to the raw bytes in the file.
However, for now, we use the FileReader class, which implicitly assumes that the file is encoded using UTF-8 (though you can specify a different encoding when creating the FileReader; that won't be necessary in this course).
The FileReader's role is to interpret the files in the appropriate encoding, and so it's core functionality is to read UTF-16 (Java's internal encoding) code points one by one.
It has a utility method that gives you all lines in a file at once, but that is often undesirable, especially for large files.
To be able to easily read a file line-by-line, we have to use a BufferedReader.
A BufferedReader requires some underlying reader, like a FileReader, to provide the actual data.
The main thing it does is provide a readLine() method, which reads the next line in the file since the last time you called it.
This is a way in which objects have behavior that changes their state. A FileReader starts at the beginning of a file and moves forward in it with every byte that it reads.
As the BufferedReader asks it to keep reading data until it reaches a line ending, each call of readLine() moves the internal state ahead by as many bytes as are needed to represent the line.