0

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.

Jo.P
  • 1,139
  • 4
  • 15
  • 35

2 Answers2

0

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() 
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I can't do the first thing you said because I need to do this check as a separate method from the read() method because of certain other things...but that second idea is a good idea it sounds like. I have to try to find some examples of those methods online...thanks! – Jo.P Nov 01 '12 at 18:37
  • My understanding (though I may be wrong) is that there are multiple things being stored in the file, and there is a function to read each thing individually, and discard the file if it's empty afterwards. The file isn't being read to the end every time. – Krease Nov 01 '12 at 18:37
  • One use of isEmpty is to let the program know not to read and create a new object (without this, it starts creating objects with null in all fields) – Jo.P Nov 01 '12 at 18:51