Input & Output (I/O)l - 1
Due to the large number of I/O classes in java.io.Files, there is a class called:
java.nio.Files
This class consists of several static function calls that cater to common use cases.
You should look in this class before looking elsewhere.
Reading from File
A classic approach to reading from a text file uses a BufferedReader to read the file line by line, and looks something like this:
File file = new File(filePathAsString);
try(BufferedReader br = Files.newBufferedReader(file.toPath())) {
String str = "";
while ((str = br.readLine()) != null) {
//do some logic with str
}
} catch(IOException ioe) {
throw ioe;
}
- The first line of this code creates a
java.io.Fileclass from a file path String (e.g. “myDirectory/myFile.txt”). -
The second line uses the
Files.newBufferedReadermethod to instantiate aBufferedReader. It takes as its first argument thePathobject associated to a file, and then allows for optional parameters that alter things like the character set. We omit these so it will have default settings and character set, UTF-8. This line is an example of try with resources, which is syntactic sugar for a lengthy try/catch construct.By declaring
brinside the try, we ensure that it will be closed, which prevents resource leaks. If we didn’t use try with resources, we’d need to callbr.close()in a finally block. - The third line just initializes an empty String.
-
The strange looking fourth line tries to read the next line of the file into
strusingBufferedReader’sreadLinemethod. Once this operation is performed, the result of that assignment isnullchecked, and ifstrhas becomenullwe know we’ve reached the end of the file. So, this is just a loop that says read every line in as aStringuntil the end of file.readLine()discards the trailing newline (\n), so if you wanted to reproduce the file’s content exactly you would need to add this back to the string. - The code enclosed by the while loop is where you would do your logic using the newly read
str. There is then a catch block that throws anIOExceptionif theBufferedReaderruns into one.
The code above is a perfectly functional way to handle file I/O, but java.nio.file.Files offers a couple of simpler alternatives to cover this use case.
Using java.nio.file.Files
Lines as an ArrayList
The first, and what is probably most useful, is Files.readAllLines(path), which returns a List of every line, in order. That looks like this:
File file = new File(filePathAsString);
ArrayList<String> yourList = (ArrayList<String>) Files.readAllLines(file.toPath());
In two lines of code we now have every line of the file, ordered, in an ArrayList we can traverse with a simple for loop. This code practically is just a tidier repackaging of the code above, where the inner loop adds str to a List<String> initialized as empty before the try.
Original File as String
Another two-liner if you just want the whole file as one big String with the white space and new lines of the file preserved, is given below:
File file = new File(filePathAsString);
String yourFilesContent = Files.readString(file.toPath());
Both the readAllLines and readString methods throw IOExceptions. This is a checked exception type so you need to throw or catch them (as in the initial example).
These methods are not performance optimised, so if you need to read a very large file in a performance intensive setting (e.g. developing an industry strength library) these aren’t the way to go. However, in most cases both are fine.