In text-based user interfaces, the input of the user is directed into the input stream one line at a time, which means that the information is sent to be handled every time the user enters a new line.
Files are collections of data that live in computers. The file format determines the content of the file as well as the program required to read the file.
The path to the file can be acquired using Java's Paths.get
command, which is given the file's name in string format as a parameter: Paths.get("filename.extension")
Reading a file may result in an error, and it's for this reason that the process requires separate blocks - one for the try
, and another to catch
potential errors.
A file is read from the project root by default ( when new Scanner(Paths.get("file.txt"))
is called), i.e., the folder that contains the folder src
and the file pom.xml
(and possibly other files as well).
Import Paths
from -import java.nio.file.Paths
try (Scanner scanner = new Scanner(Paths.get("file.txt"))) {
// we read the file until all lines have been read
while (scanner.hasNextLine()) {
// we read one line
String row = scanner.nextLine();
// we print the line that we read
System.out.println(row);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
scanner.hasNextLine()
to check if file has any more content.
Reading objects from a file is a clear responsibility in and of itself, and should for that reason be isolated into a method.