How to Read a File Line by Line in Java

0 min read 139 words

If you need to read a file line by line in Java, then you can use one of the following three (3) options.

Option 1

You can use the FileReader and BufferedReader packages as follows:

File file = new File("./your/file.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();
}

Option 2

You can also read the lines using Files and Paths as follows:

Path filePath = Paths.get("./some/directory", "file.txt");
 
try (Stream<String> lines = Files.lines( filePath )) {
  lines.forEach(System.out::println);
} 
catch (IOException e) {
  e.printStackTrace();
}

Option 3

You can also use the FileUtils class from Apache Commons IO as follows:

File file = new File("./your/file.txt");

try {
  List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
} catch (IOException e) {
  e.printStackTrace();
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts