Java reader readline while

while loop with a readLine()

and statements execute until condition becomes false and the loop is over. I’m interested in logic of this kind of statement:

It’s used in client — server communication in my case. The condition is sometimes true, sometimes isn’t, but loop looks like it’s testing the condition forever and when true, statements in <> execute. It looks to me that loop waits for the condition to be true and then runs statements. Is it somehow linked to the way BufferedReader and InputStreamReader work or what? Also, it seems this loop is never over, it just waits for a condition to be true and then runs statements, and then again waits for a condition to be true , etc. I would be thankful for any clarification.

@3kings Nonsense. You can’t ‘send a null object’. The loop terminates when readLine() returns null, which it does at end of stream. See the Javadoc.

Understood, but, when readLine() exhausted all lines, loop still isn’t over(though condition becomes false), it waits for another line to appear (from server) to be read, and again runs its code and it looks that this loop is forever alive waiting for condition to be true. If condition is false(when there’s nothing to read) it still isn’t dead, it waits for situation when condition will become true again

The only tricky thing about that line is that has a comparison on an expression with an assignment. It assigned the a for later use, before checking the value. This is part of the language and nothing to do with the class.

Читайте также:  Utf 8 html wiki

4 Answers 4

At each iteration, the condition inside the parentheses is evaluated.

Evaluating this expression consists in calling b.readLine() , affecting the returned value to a , and comparing a with null.

Calling readLine() , as documented, consists in blocking until the next line is read. If there is no next line, readLine() returns null.

So, in short, this while loop reads every line from the reader, does something with the line (inside the while block) and stops when the end of the stream is reached.

The following code snippet

String a; while((a = b.readLine()) != null) < // a = b.readLine() ->a -> a != null . > 
String a = b.readLine(); while(a != null)

but the first way is more simple, readable, and Java allows using assignment operators here because they return the value of a renewed variable.

Dear Andrew, I’m afraid you are very wrong, both codes are not the same. The first one like you have rightly said is the correct one but the second code will loop forever when something is read by b.readLine().

while ( (a = b.readLine()) != null) < /* body */ >

is a normal while loop, but the condition happens to contain an embedded assignment operator, which yields the result of the assignment, which is compared to null .

Whether b is reading from a socket, a file, or any other input stream, presumably b is something like a BufferedReader with its readLine() method. This method will only return null when the end of the stream is reached. It will block if the end of the stream hasn’t been reached yet, but not further input consisting of a newline character has been read off the stream yet.

When such a line is available, a is not null and the body of the loop executes. The result of readLine is assigned to a for convenient processing withing the body of the loop.

When the end of the stream is reached, a is null and the while loop ends.

This idiom allows for easy processing of an entire stream of data, whether it is from an entire file, from an entire socket connection, or otherwise generally reading from an entire input stream of data. It looks more complicated than a simpler while loop, but it’s just a standard while loop with a more complicated condition.

Источник

Using BufferedReader.readLine() in a while loop properly

The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won’t work. Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up. I don’t get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?

7 Answers 7

try < InputStream fis=new FileInputStream(targetsFile); BufferedReader br=new BufferedReader(new InputStreamReader(fis)); for (String line = br.readLine(); line != null; line = br.readLine()) < System.out.println(line); >br.close(); > catch(Exception e)

This is the way to go for me. while((line=br.readLine())!=null) is just too ugly. I don’t like calling br.readLine() twice but there is not much you can do about that. I would just shorten the for statement to for (String s = br.readLine(); s != null; s = br.readLine())

I like the for loop syntax so you don’t have a variable hanging around after the loop. Also it can be shortened a bit, still kind of ugly: for ( String line = null; null != (line = reader.readLine()); ) Note: using reader.readLine() in the conditional and the initializer of the for causes the first line to be skipped.

I don’t know java well, so this is probably not the cleanest fix, but when a program can’t open a file, it should give a useful error message explaining why. In other words, don’t throw away important information; include it in the error message. eg, System.err.println(«Error: Target File Cannot Be Read» + e);

doesn’t it take a lot of memory because in every loop its creating a string object and assigning the reference «line» to that object and also leaving the older string object to be garbage collected. We all string is immutable . can’t we use StringBuilder in some way

Источник

BufferedReader readLine used in while loop

I have seen BufferedReader using while loops to iterate through the contents of a file, with code more or less like:

what I don’t understand is how the while loop is internally incrementing its counter until it has read all lines in the document. To me, the while loop above means «if the first line (line[0]) is not null, do something (presumably an infinite number of times)», and never advancing past the first line of the document. What am I not understanding about BufferedReader or the .readLine() method?

4 Answers 4

I hope I get your question right. You would like to know how BufferedReader determines where to continue reading within the loop without a counting variable?

If you take a look inside BufferedReader.class you will see a private int pos; counter that is incremented every time a char is read from the stream, e.g. in public int read() . Same is happening in readLine() with the difference that pos is incremented until the end of the line is reached.

You can reset the internal counter using reset() function (this is to the last mark location, see here for details).

Yes, that is what I was trying to ask. I couldn’t see any way the loop was counting so as to advance to the next line of the input file. I looked at the BufferReader.class page on the Oracle site, but I could not find private int pos; anywhere. Could you send me a link so I can see just where it is? (to satisfy my own personal curiosity). Thx.

You can view the source for BufferedReader on developer.classpath.org/doc/java/io/BufferedReader-source.html (see line 74 for pos counter). Or: If you are using Eclipse just select BufferedReader in the editor and press F3 🙂

The line inside braces of the following while loop:

while ( (line = br.readLine()) != null ) 

And the method readLine() will keep on reading the next line from the file and once it reaches the end of the file it returns null . So it works this way.

On a side note there is no restriction of a counter for while loop, only thing it needs is an boolean expression that evaluates to true or false.

firstly, Its necessary to understand the difference between Filereader and Buffered Reader. Buffered Reader reads text from a character-input stream,buffering characters so as to provide for the efficient reading of characters,arrays and lines. Whereas FileReader reads a line of text.A line is considered to be terminated by one of the line feeds or a return. Just Keep in mind that While would execute when the first line in a file is not empty.Even if there is a single dot there it would read it. Hope It helps Now. 🙂 Comment below for further details. Have a nice day.

while ( (line = br.readLine()) != null ) < // do something >

First line is assigned to whatever br.readLine() returns, then line is compared to null. The parenthesis enforce that order of operations.

The variable line will keep taking on the value of the text of the next line as the program loops through all lines in the file, until it reaches the end of the file. At that point line is assigned the value null, which then terminates the loop.

what I don’t understand is how the while loop is internally incrementing its counter

There is no counter for this loop. The loop termination condition is line == null (another way of saying it keeps looping while line != null ). The loop ends when line is null.

To me, the while loop above means «if the first line (line[0]) is not null

No, line is not an array. It is a string representing a single line of the file, and that value gets updated as each line is read from the file.

string[] allLines = File.ReadAllLines(path); 

That different approach reads all lines of the file into memory at once. That method is handy for reading in small files, while the method you present is much more memory efficient. It streams the contents of the file, only allocating memory for the current line. That approach is far superior for large files.

Note that the buffered reader plays no role in the loop semantics. It is simply a mechanism to more efficiently read the file from disk (or perhaps unnecessary overhead).

Источник

Reading lines with BufferedReader and checking for end of file

How can I avoid a crash if the next line is the end of the file? (i.e. null) I need to read the next line because there may be something there that I need to deal with but if there isn’t the code just crashes. If there is something there then all is OK, but I can’t be guaranteed that there will be something there. So if I do something like: (pseudo code):

if (r.readLine is null) //End code else

The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again? I’ve not worked out a way to do this — any suggestions would be a great help.

Really wish people would leave a reason when down-voting. A down-vote is supposed to indicate there is something wrong with a question so maybe it can be reformatted. Down-voting without leaving a reason as to why the downvote has been cast helps no-one

8 Answers 8

Am. You can simply use such a construction:

String line; while ((line = r.readLine()) != null) < // do your stuff. >

If you want loop through all lines use that:

while((line=br.readLine())!=null) < System.out.println(line); >br.close(); 

You can use the following to check for the end of file.

public bool isEOF(BufferedReader br) < boolean result; try < result = br.ready(); >catch (IOException e) < System.err.println(e); >return result; > 

This fails silently on exception and BufferedReader::ready can return false even if the next read will succeed.

In your case you can read the next line because there may be something there.If there isn’t anything, your code won’t crash.

String line = r.readLine(); while(line!=null)

A question in the first place, why don’t you use «Functional Programming Approach«? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-

import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; public class LineOperation < public static void main(String[] args) throws IOException < Files.newBufferedReader(Paths.get("C://xyz.txt")). lines(). collect(Collectors.toSet()). // You can also use list or any other Collection forEach(System.out::println); >> 

Источник

Оцените статью