1

I have a method that read the next line in a txt file and does something. I have another method that needs to check for EOF as well. The two methods are called receptively within a loop.

method 1:

trace = br.readLine();
   if (trace==null)
       break; // end of file

method 2: I need to check for EOF without using the same technique. Otherwise, it would increment the ptr used for readLine...

Is there any way to accomplish this?

Thanks

vyegorov
  • 21,787
  • 7
  • 59
  • 73
Hank Liu
  • 85
  • 1
  • 3
  • 9
  • check this question: http://stackoverflow.com/questions/2517638/can-i-peek-on-a-bufferedreader and this answer: http://stackoverflow.com/a/2517713/1227804 – user1227804 May 06 '12 at 15:24

3 Answers3

2

Is there any way to accomplish this?

The BufferedReader API doesn't allow you to do this (*). If you really need to do this, you'll need to implement a custom Reader class to do this. I'd start with PushbackReader, add a readLine() method and then implement an eof test method by reading one char and pushing it back.

* From reading the answers to Can I peek on a BufferedReader?, it appears that the ready() method might work as an EOF test. However, this is an artifact of the current implementations of ready() in the standard code-base, and is arguably wrong (a bug) according to the javadoc specification of the method.

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You can use

 Scanner sc = new Scanner (file);

and read

 while (sc.hasNext ())

Scanner has a

  sc.readLine (); 

method.

user unknown
  • 35,537
  • 11
  • 75
  • 121
  • This generic answer doesn't begin to solve OP's specific request to check for EOF at two places in the code. – Marko Topolnik May 06 '12 at 16:30
  • @MarkoTopolnik: Wrong! `Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.` You can invoke the method at different points. – user unknown May 06 '12 at 16:59
0

You can use this format to check as well to avoid EOF exception. Since the buffer size is determined early it will not cause any error to occur.

File myFile = new File("path");
String completeText = "";
FileChannel fc = new FileInputStream(myFile.getAbsoluteFile()).getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int)fc.size());
fc.read(buffer);
Charset charset = Charset.defaultCharset();  
CharsetDecoder decoder = charset.newDecoder();  
CharBuffer charBuffer = decoder.decode(buffer);    
completeText = charBuffer.toString();
buffer.clear();
fc.close();
Arun Chettoor
  • 1,021
  • 1
  • 12
  • 17