Problem open a file and read content
How to open and print out the content of text file by using java 8
Solution using BufferedReader
Method openFilePrintAll will open local file using Java's BufferedReader. It's will read it line per line and it'll print all lines.
Method openFileSearch will check every line for word 'test' and if it's there it will print the line. In case of error than No such file will be printed to the console.
package fileAccess;
import java.io.*;
public class Files {
public static void main(String[] args) {
openFileSearch();
openFilePrintAll();
}
//method for openning text file
static void openFileSearch() {
try {
BufferedReader input = new BufferedReader(
new FileReader("C:\\Users\\user\\Desktop\\text.txt"));
String line;
while ((line = input.readLine()) != null)
if (line.indexOf("test") != -1)
System.out.println(line);
input.close();
} catch (IOException ex) {
System.err.println("No such file");
}
}
//method for openning text file
static void openFilePrintAll() {
try {
BufferedReader input = new BufferedReader(
new FileReader("C:\\Users\\user\\Desktop\\text.txt"));
String line;
while ((line = input.readLine()) != null)
System.out.println(line);
input.close();
} catch (IOException ex) {
System.err.println("No such file");
}
}
}