• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in reading empty line

 
babu sharath
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI ,
I want to read the file and print the contents of file.
For that I wrote :

File file = new File("test_file");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (line=br.readLine()) != null )
{
line = line.trim();
System.out.println( line );
}

Above is working if there is no blank lines in the file.
If file is like below :
test1
test2

test3
End of file.

Then it is printing first two lines only.Because 3rd line is empty.
How to handle this situation ? Is readLine() takes that empty line as null ?

Regards,
Sharath
 
babu sharath
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI ,
Sorry I didn't wrote the complete code earlier :

File file = new File("test_file");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while( (line=br.readLine()) != null )
{
line = line.trim();
System.out.println( line );
if (line.charAt(0)=='#')
{
continue;
}
}
( When a line starts with a # I want to ignore that )
In above senario , file is read upto empty line and next lines were not read
what is the problem with above code ?

Sharath
 
prashanth kumar
Ranch Hand
Posts: 162
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I remember using ready() method when i wrote code long time back..
So try to put an AND condition in your while loop using ready() method..There may be some better ways as well...
 
Jae Stryker
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Hi could your problem be within the while loop - i.e. you are looping until it finds a null line (which a blank line could be), would it not be better to use an end of file marker - This is only a suggestion of course.
 
wise owen
Ranch Hand
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


readLine() just returns "", the empty string, for an empty line.

[ October 31, 2006: Message edited by: wise owen ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following on from what "wise owen" writes, I guess that the original poster is throwing away exceptions - correct?
 
Nikhil Bansal
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Babu Sarath,

Try using StringReader class (JDK 1.5 API) instead of BufferedReader. Use the read method, which will read data from the file till EOF is reached.

Hope it helps.

Regards

Nikhil Bansal
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic