How to Read a File Line by Line in Java

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(); }
Code language: Java (java)

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(); }
Code language: Java (java)

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(); }
Code language: Java (java)

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments