In this example we will show the method to read a file in Java.
Source Code
package com.beginner.examples;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadFile {
public static void main(String[] args) {
try {
File f = new File("example.txt");
Scanner reader = new Scanner(f);
while (reader.hasNextLine()) { // read a file
String content = reader.nextLine();
System.out.println(content);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
test
References
Imported packages in Java documentation: