Read
Lesson 4 of 11 in Coddy's File Handling in Java course.
One way to read file content in Java is by using the Scanner class, which is also used for getting input:
try {
File dataFile = new File("data.txt");
Scanner scanner = new Scanner(dataFile);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
System.out.println(data);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}The above code, reads and prints every line in the "data.txt" file.
Note that you must wrap the code with try-catch and handle the
FileNotFoundExceptionexception
Challenge
EasyYou are given the same file as before "coddy.txt", read and print its content, line by line.
Notice the pre added (and needed) imports!
Try it yourself
import java.io.File;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// Write code here
}
}