• Post Reply Bookmark Topic Watch Topic
  • New Topic

Does a BufferReaderobject remember its last location if you pass it on to a new method? [SOLVED]  RSS feed

 
Bernard Rosseel
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I am busy on my own project and I am fairly new with Readers so my apologies if my question is very amateur .

createBufferReader(){
BufferedReader br = new BufferedReader(new FileReader(new File(...)));
br.readLine();
br.readLine();
secondMethod(br);

secondMethod(BufferedReader br){
br.readLine(); // will the br continue from the first line of the file or the one he last read in the createBufferReader method?

Thank you for your time and patience .

Found it
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Please don't edit your post like that; it makes it difficult to reply. And please beware of writing SOLVED; you might have found the answer to your question but you may not have solved your problem. You were right to try it out; that is often quicker than waiting for a reply.

No, a buffered reader continues from where it left off. It does not normally go back to the beginning, but it has mark and reset methods which allow you to go back if you use them.
But it is probably a mistake to pass the reader to another method, maybe less so if you wrote the method yourself. The other method may do something with the reader which affects its use later on. A buffered reader is intended to be used in one method, to read from a file, and then (unless it points to System.in or similar) it must be closed. Once. Because you have two methods, your reader might be closed once, twice or never. You can get problems if the reader does not close (the file might not be accessible) or if it is closed twice (Exceptions).
So you should use a reader in one method and make sure it is closed. The best way to close it is probably with Try With Resources.
 
Bernard Rosseel
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah I see, my apologies.

Yes I created it myself those methods.
Thank you for the advice on closing it ,I hadn't considered that yet.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!