Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

readLine method

 
swapna marepally
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you please
clarify this bit of code

i wrote code to read data in a file

the following code is reading only first line of file (please clarify why)
import java.io.*;


class File1
{

public static void main(String args[]) throws IOException
{

try
{

File f=new File("bag.txt");
f.createNewFile();
// the fiel will be created in the current directory path i.e. in this path itself
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String data=br.readLine();
System.out.println("the content in the file is");
System.out.println(data);
br.close();

}catch(FileNotFoundException fn)
{
System.out.println(" the file is not found");
}


}


i wanted to read the whole text

i wrote like this

took a while loop

while (data!=null)

but it is going to infinite loop printing the first line

but in text book i found the code like this
and it is perfectly working

String data;
while((data=br.readLine())!=null)

can you please explain it elaborating bit by bit
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code you posted doesn't have a loop, so it certainly will only process one line.

Show us the code with the loop, and we will see whether we can spot the error.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Do you know what exactly this means?



At each iteration readLine() must me executed so that it could move forward.
Your previous attempt was just contrary to this. You called readLine() only once, and what you did next in the loop I need not to say; so infinite loop
(value of data was not changing).


Regards,
cmbhatt
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since this is the beginner forum, let's take a second to disect that line:

while((data=br.readLine())!=null) {
}

The bit that may be surprising is that an assignment statement like data=br.readLine() is also an expression with a value which happens to be the value that was just given to the left side of the =. So every time through the loop, this reads from the file, assigns the value to the variable data, and checks the value for null. Pretty slick once you get used to the syntax.

This is a very common way to read files or other BufferedReaders. Write it down for future use if you're afraid you might forget.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic