In this Java tutorial, we will learn to read a file line by line using various methods. We will also learn to iterate through lines and filter the file content based on some conditions.
1. Reading with Stream of Lines
In this example, we will read the file contents one line at a time using Java Stream API and fetch each line one at a time and check it for word "password"
.
Path filePath = Paths.get("c:/temp", "data.txt");
//try-with-resources
try (Stream<String> lines = Files.lines( filePath ))
{
lines.forEach(System.out::println);
}
catch (IOException e)
{
e.printStackTrace();
}
We can also use the Files.readAllLines() method that reads all lines from a file into a List. By default, bytes from the file are decoded into characters using the UTF-8
charset
.
Path filePath = Paths.get("c:/temp", "data.txt");
List<String> lines = Files.readAllLines(filePath);
2. Reading and Filtering the Content
In this example, we will read the file content as a stream of lines as. Then we will filter all lines which have the word “password” in them.
For filtering, we are passing a lambda expression, that is an instance of a Predicate, to the filter() method.
Path filePath = Paths.get("c:/temp", "data.txt");
try (Stream<String> lines = Files.lines(filePath))
{
List<String> filteredLines = lines
.filter(s -> s.contains("password"))
.collect(Collectors.toList());
filteredLines.forEach(System.out::println);
}
catch (IOException e) {
e.printStackTrace();
}
We are reading the content of the given file and checking if any line contains word "password"
then print it.
3. Reading a File Line by Line using FileReader
Till Java 7, we could read a file using FileReader
in various ways.
File file = new File("c:/temp/data.txt");
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
4. Guava Files.readLines()
One of the simplest solutions is to use the Google Guava’s Files class its method readLines().
try {
List<String> lines = com.google.common.io.Files.readLines(file,
Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
If we want to process the lines as they are read, we can use a LineProcessor. For example, in the below code, we are capitalizing the lines as they are read.
// With LineProcessor
LineProcessor<List<String>> lineProcessor = new LineProcessor<>() {
final List<String> result = new ArrayList<>();
@Override
public boolean processLine(final String line) throws IOException {
result.add(StringUtils.capitalize(line));
return true; // keep reading
}
@Override
public List<String> getResult() {
return result;
}
};
try {
List<String> lines = com.google.common.io.Files
.asCharSource(file, Charset.defaultCharset())
.readLines(lineProcessor);
} catch (IOException e) {
e.printStackTrace();
}
5. Commons IO’s FileUtils.readLines()
Similar to Guava, Apache Commons IO library has FileUtils class that provides a single statement solution for reading the file content in lines. The file is always closed at the end of the operation.
try {
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
That’s all for Java example to read a file line by line. Please put your questions in the comments section.
Happy Learning !!
Hi ,
I want read certain word like ” Result ” . I need to print all line after result line.
please share me code.
Thanks in advance
Hi,
Have assigned with a task to create a Data Collector using NIO and TFTP.
From the Network Elements i have to get large files using TFTP and Java NIO.
Could you please help me to do this.
You must try yourself first, if struck anywhere then let me know.
Awesome Lokesh…really nice article.
Hi,
I am student of MTech.I have to do thesis work,where I have to read text and find the maximum probability of a particular Indian languages with Java.Suggest me how would I do that….
hi i’m a vivid follower of