Now i am giving you some Java 8 read file line by line examples which are very useful for programmer everyday. Reading files line by line using java IO and perform some operations of lines. By the way, i also mention the classic ways to read using BufferedReader And Scanner.
In this article, i are considering the text file named “test.txt” which are used in all examples.
1. Java 8 read file into stream
In this example, I will read the lines as stream and fetch each line one at a time and check it for string “8”.
One more thing, here i’m using try-with-resources which will take care of the closing the stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public static void main(String args[]) { String fileName = "D://test.txt"; List<String> list = new ArrayList<>(); //The stream hence file will also be closed here try (Stream<String> stream = Files.lines(Paths.get(fileName))) { // do stuffs as filter, upper case, etc. list = stream.filter(line -> !line.startsWith("222")).map(String::toUpperCase) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } list.forEach(System.out::println); } |
Ouput
1 2 3 4 5 6 |
JAVA READ FILE LINE BY LINE |
2. Java 8 Bufferedreader example
Java 8 Bufferedreader is added a new method lines(). It lets BufferedReader returns content as Stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static void main(String args[]) { String fileName = "D://test.txt"; List<String> list = new ArrayList<>(); try (BufferedReader bufReader = Files.newBufferedReader(Paths.get(fileName))) { //bufReader returns as stream and convert it into a List list = bufReader.lines().collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } list.forEach(System.out::println); } |
Output
1 2 3 4 5 6 7 |
Java 8 read file line by line |
3. Classic BufferedReader And Scanner
By the way, we revisit the classic BufferedReader (JDK1.1) and Scanner (JDK1.5) examples to read a file line by line. So you can compare this classic way to the new way of Stream.
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 |
public static void main(String args[]) { String fileName = "D://test.txt"; //using classic BufferedReader try (Scanner scanner = new Scanner(new File(fileName))) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); } } catch (IOException e) { e.printStackTrace(); } //using Scanner try (Scanner scanner = new Scanner(new File(fileName))) { while (scanner.hasNext()){ System.out.println(scanner.nextLine()); } } catch (IOException e) { e.printStackTrace(); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Java 8 read file line by line Java 8 read file line by line |
That’s all about Java 8 read file line by line examples.
References
Java 8 File.lines()
Java BufferedReader
Download the complete source code, click link below
Java8StreamReadFile.zip (320 downloads)