- Reading a text file line by line in java can be done by using java.io.BufferedReader .
- Create a BufferedReader class by passing new FileReader(new File("filename")) object to it's constructor.
- By using readLine() method of BufferedReader class we can read line by line text from a text file as Strings.
- Lets see a java example program on hoe to read data from file line by line using BufferedReader class readLine() method.
- Java read lines from text file example program.
#1: Java Example program to read file line by line
- package com.instanceofjava.readfile;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- /** * *
- @author www.instanceofjava.com
- * @category: Interview Programs
- * @description: How to read text file line by line in java example program
- * */
- public class ReadFile {
- public static void main(String[] args) {
- try {
- File fileName = new File("E:\\data.txt");
- FileReader fileReader = new FileReader(fileName);
- BufferedReader bufferedreader = new BufferedReader(fileReader);
- StringBuffer sb = new StringBuffer();
- String strLine;
- while ((strLine = bufferedreader.readLine()) != null) {
- sb.append(strLine);
- sb.append("\n");
- }
- fileReader.close();
- System.out.println(sb.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Output:
- java read file line by line example
- java read file line by line java 8
- java read lines from text file
- example bufferedreader java example
#2: Java example program to read text file line by line using java 7 try with resource example
#3: Java example program to read text file line by line using java 8 example (Using stream)
- package com.instanceofjava.readfile;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.util.stream.Stream;
- /**
- *
- * @author www.instanceofjava.com
- * @category: Interview Programs
- * @description: How to read text file line by line in java example program using java 8 stream
- *
- */
- public class ReadFile {
- public static void main(String[] args) throws IOException {
- try (Stream<String> stream = Files.lines(Paths.get("E:\\data.txt")))
- {
- stream.forEach(System.out::println);
- }
- }
- }
No comments