This exercise is reserved for pair programming in the live lab sessions.
Please skip it when doing the exercises individually.
The In library from stdlib makes it easy to read text files into your programs. Here is an example where we read in text from a URL, then iterate through the file reading one line at a time.
In file = new In("http://www.gutenberg.org/files/39063/39063-0.txt"); while (!file.isEmpty()) { String line = file.readLine(); if (line.contains("mountain")) { System.out.println(line); } }
Experiment with this code, for example by opening other files, and searching for other words in lines.
You can also use In to read in local text files. If you are compiling Java from the command-line, then put these files in your working directory. However, if you want to read data from files within IntelliJ, be aware of your working directory again and adapt file paths accordingly!
Rather than looping over lines or words, you can use In to read the whole file into a string. If the string is long, you might want to split it up at whitespace, as shown here:
In file = new In("myfile.txt"); String s = file.readAll(); String[] words = s.split(" ");
For more information about the methods it supplies, refer to the API for In.
With Java version 11, a similarly easy way for reading and writing files is provided in the class java.io.Files. This class provides static methods such as writeString to write a text to a specified file or readString to read all content from a file. Have a look at the corresponding Java API.
To make handling files easier, Java also provides the classes java.io.File and java.nio.file.Path which you might want to look at.
Note
For the purpose of the labs, you can decide yourself if you want to use the external library or the Java API classes.