Home > Java > Read File Line by Line

Read File Line by Line

Many ways to do it in java and this is one example of them.


public class LineReader {

public void readByLine(String filename) {

BufferedReader reader = null;

try {

try {

reader = new BufferedReader(new FileReader(new File(filename)));

String content = null;

while ((content = reader.readLine()) != null) {

System.out.println(content);

}

} finally {

reader.close();//dont forget to close the reader

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

String content = null;

}

public static void main(String[] args) {

new LineReader().readByLine("I:\\text_file.txt");

}

}

I’m using input file containts these lines:

hai, this is line 1
this is line 2
and this line 3
line 4 and adieu...

and the output came exactly it has to be.

Advertisements
Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: