cancel
Showing results for 
Search instead for 
Did you mean: 

FileInputStream: Why null, when System.out.println(br.readLine());

Former Member
0 Kudos

Hi,

I am reading a local file:

why is the follwing giving a null for the last line of the file?

		try {
	FileInputStream fstream = new FileInputStream(filename);
	// Get the object of DataInputStream
	DataInputStream in = new DataInputStream(fstream);
	BufferedReader br = new BufferedReader(new InputStreamReader(in));
	// Read File Line By Line
	String strLine = "";
//	while ((strLine = br.readLine()) != null) {
	while (br.readLine() != null) {
	 System.out.println(br.readLine());
	}// while
	// Close the input stream
	in.close();
	} catch (Exception e) {// Catch exception if any
	System.err.println("Error: " + e.getMessage());
	}

but thze following works OK?


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

Thanks regards

mario

Edited by: Mario Müller on Nov 7, 2009 1:12 PM

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Hello Mario,

The reason is that in the following code you are reading a line in the while clause and then you are reading another line in the println clause.


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

	}

Therefore when you read the last non null line in the while clause, the println will try to read the next and get null.

Cheers,

Ventsi Tsachev

Technology Development Support (J2EE Engine)

SAP Labs, Palo Alto, Ca (USA)

Answers (0)