In this post, we will see different ways to read file line by line in java.
Sometimes, we need to read file line by line to a String, and process it.
Here are different ways to read file line by line in java.
Table of Contents
Java 8 Streams
Java 8 has introduced a new method called lines()
in Files
class which can be used to read file line by line.
The advantage of using this approach is that it will return Stream
of String which will be populated lazily as Stream is used. In case, you need to read the large file and require only first 1000 lines to read, then this is the best approach as it will not rest of the file in memory which will result in better throughput.
Another advantage is that you can use different Stream
methods to perform the operation on Stream such as filter, map, etc.
Let’s see this with the help of an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.arpit.java2blog; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class ReadFileLineByLineMain { public static String fileName="/users/apple/"; public static void main(String[] args) { Path filePath = Paths.get("/users/apple/Desktop/employees.txt"); try (Stream<String> lines = Files.lines( filePath )) { lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
Let’s say you want print all male employees.You can use filter method to filter all the male employees.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package org.arpit.java2blog; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ReadFileLineByLineMain { public static String fileName="/users/apple/"; public static void main(String[] args) { Path filePath = Paths.get("/users/apple/Desktop/employees.txt"); try (Stream<String> lines = Files.lines( filePath )) { List<String> maleEmp = lines.filter(emp -> emp.contains("Male")) .collect(Collectors.toList()); maleEmp.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
Using BufferReader
You can use java.io.BufferReader
‘s readLine()
method to read file into String line by line.Once you reach end of the file, it will return null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.arpit.java2blog; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileLineByLineMain { public static void main(String[] args) { String fileName = "/users/apple/Desktop/employees.txt"; try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; //br.readLine() will return null when end of file is reached while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } |
Using Scanner
You can use java.util.Scanner
class to read file line by line. You can use hasNextLine()
method to check if there are more lines to read and nextLine()
to retrieve current line and move the read position to next line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.arpit.java2blog; import java.io.File; import java.io.IOException; import java.util.Scanner; public class ReadFileLineByLineMain { public static void main(String[] args) { String fileName = "/users/apple/Desktop/employees.txt"; try (Scanner scanner = new Scanner(new File(fileName))) { while (scanner.hasNext()){ System.out.println(scanner.nextLine()); } } catch (IOException e) { e.printStackTrace(); } } } |
Scanner class divides its input into token using delimiter, which is either line feed("\n") or carriage return("\r".) in our case.
Using Files
You can use java.nio.file.File
‘s readAllLines
method to read file into list of String.
It may not perform well in case you have large file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package org.arpit.java2blog; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class ReadFileLineByLineMain { public static void main(String[] args) { ReadFileLineByLineMain rfllm=new ReadFileLineByLineMain(); String fileName = "/users/apple/Desktop/employees.txt"; List<String> lines = rfllm.readFileLineByLine(fileName); for (String line : lines) { System.out.println(line); } } public List<String> readFileLineByLine(String fileName) { List<String> lines=null; try { lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } return lines; } } |
Using RandomAccessFile
You can also use RandomAccessFile's
readLine()
method to read file line by line in java. You need to open file in read mode and then call readLine()
method to read file line by line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog; import java.io.IOException; import java.io.RandomAccessFile; public class ReadFileLineByLineMain { public static String fileName="/users/apple/Desktop/employees.txt"; public static void main(String[] args) { try { RandomAccessFile file = new RandomAccessFile(fileName, "r"); String str; while ((str = file.readLine()) != null) { System.out.println(str); } file.close(); } catch (IOException e) { e.printStackTrace(); } } } |
Using Apache Commons
In case you prefer to use Apache commons library, you can use FileUtils
‘s readLines
method to read file into the list.
You need to include following dependencies in pom.xml.
1 2 3 4 5 6 7 |
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.FileUtils; public class ReadFileLineByLineMain { public static String fileName="/users/apple/Desktop/employees.txt"; public static void main(String[] args) { List<string> lines; try { lines = FileUtils.readLines(new File(fileName), StandardCharsets.UTF_8); lines.forEach(System.out::println); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </string> |
Please note that this approach may not be well optimized. It will read the complete file into a list which can perform badly in case of large files.
That’s all about how to read file line by line in java.