0

I search the content in a file line by line using a while loop until I find the String 'MATCH'. But when in another function I need to use BufferReader again, will it refer to the end of file or start from the very beginning of the file?

Public String method1(String match){
  String line;
  while((line = bufferReader.readLine()) != null){
  if (line = match)
  return line;
  }
}

Public String method2.......

When implementing method 2, will bufferReader point to the place when line = match? Or bufferReader will be re-initialised to the beginning of the file?

evanchen
  • 3
  • 2
  • 2
    Your if syntax is wrong (it needs == ), please correct that. – jatanp Sep 04 '14 at 18:42
  • 1
    Take a closer look at `=` & `==`. Never compare String in Java with `==` instead use `equals()` method of `Object` class. – OO7 Sep 04 '14 at 18:47
  • Have a look at these post http://stackoverflow.com/questions/17269329/how-to-read-a-bufferedreader-twice-or-multiple-times & http://programmers.stackexchange.com/questions/123200/sharing-buffer-between-multiple-threads – OO7 Sep 04 '14 at 18:55
  • What happened when you tried this? – Peter Lawrey Sep 04 '14 at 20:15

1 Answers1

2

The position of the BufferedReader is "shared" among all places where it's used. If you read lines until you reach a "MATCH", and use the BufferedReader in another method, it will continue from that line.

Also,

if (line = match)

doesn't look right. You're probably after

if (line.equals(match))
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Is there a method to initialise BufferedReader? – evanchen Sep 05 '14 at 19:43
  • To reset it to read from the beginning again? No, you could try this though: http://stackoverflow.com/questions/5034311/multiple-readers-for-inputstream-in-java – aioobe Sep 06 '14 at 05:22
  • If I closed FileReader, will the BufferedReader read from the beginning again? – evanchen Sep 06 '14 at 06:00
  • If you close the underlying FileReader you will no be able to use the BufferedReader. Why don't you simply recreate a new buffered reader / file reader if you want to start over from the beginning? – aioobe Sep 06 '14 at 06:12