Sunday, September 11, 2011

Java Code to read file line by line


This sample java code shows how to read file line by line. First, open a FileReader then filter this through a BufferedReader to read the file line by line.

Java Source Code

Note : While opening a FileReader we pass path of file to be read placed at your local machine in its constructor. Please make sure that path and name of file is correct otherwise code will throw FileNotFoundException & IOException.


public class ReadFile {
            public static void main(String[] args) {
                        try {
                                    /*
                                     * Open a FileReader and give path of file placed at your local
                                     * machine
                                     */
                                    FileReader input = new FileReader("C:\\SampleFile.txt");
                                    /*
                                     * Filter FileReader through a BufferedReader to read the file line
                                     * by line
                                     */
                                    BufferedReader bufRead = new BufferedReader(input);
                                    String line;
                                    int count = 0;
                                    // Read first line
                                    line = bufRead.readLine();
                                    count++;
                                    // Read file one line at time.
                                    while (line != null) {
                                                System.out.println(line);
                                                line = bufRead.readLine();
                                                count++;
                                    }
                                    // close all open resources
                                    bufRead.close();
                        } catch (IOException e) {
                                    // catch all IOExceptions
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    // catch all other exceptions
                                    e.printStackTrace();
                        }
            }
}


1 Responses to “Java Code to read file line by line”

Ravi said...
February 8, 2012 at 6:20 AM

Good code for Beginners to learn


Post a Comment

© 2011 a2ztechguide.com • All rights reserved.
Blogger Template by Bloggermint