Monday, 13 August 2018

//How to read file content line by line in java?


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadLinesFromFile {

    public static void main(String a[ ]){
        BufferedReader br = null;
        String strLine = "";
        try {
            br = new BufferedReader( new FileReader("d:/govindjava.txt"));
                                                  //or
            //br = new BufferedReader( new FileReader("d:\\govindjava.txt"));
            while( (strLine = br.readLine()) != null){
                System.out.println(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }
    }
}





//How to read file content line by line in java?(try with resources concept-java 7 concept)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadLinesFromFileJava7 {


public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader("d:/try-with-resources.txt"))) {

String  str=" ";

while ((str = br.readLine()) != null) {
System.out.println(str);
}

} catch (IOException e) {
e.printStackTrace();
}

}

}












No comments:

Post a Comment