Question

I am trying to read from a text file and use the input to create multiple different objects. I obviously don't want to keep reading after the file is empty, so I have a method isEmpty() which reads up until the point I want in the file and then reads the next line and tests for null.

The problem is that if it's not empty it then goes onto read the file...but from the NEXT line. In other words, I read the first line to test but then can't read it again.

My current idea is to create a dummy object to test this on and use an identical, second object to actually use. But this seems kind of wasteful and I think there must be a better way....thanks everyone!

Notes: The method which reads is not the same method that is checking for empty. The same bufferedReader is being used throughout the object's methods because otherwise I will need to ask the user to enter the file name again, which I don't want to do.

Was it helpful?

Solution

Why don't you stick to the BufferedReader idiom? Instead of asking if the file is empty, and get the next item if it's not empty, directly ask for the next item, and have the method return null if there is no item anymore. Much simpler:

while ((line = reader.readLine()) != null) {
    ...
}

Otherwise, you could use mark() to mark your current position, read ahead some lines, and then reset() to go back to your mark.

OTHER TIPS

I am thinking that you may want to use RandomAccessFile, this has functions to support skip and is capable of moving backwards.

You may be interested in using methods below:

  void  seek(long pos) 
  int   skipBytes(int n) 
  String    readLine() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top