Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About reference one by one and reader closing

Tags:

java

I have two short questions.

Here is the first

  //global
  private static final URL ca = Administrator.class.getResource("category.txt");

  //inside some method
  BufferedReader br = new BufferedReader(new FileReader(new File(ca.getFile())));
  br.close():

Is this a good practice? I mean I embed FileReader as a parameter, so I may not be able to close it. And I suppose java may be smart enough to close it when br is closed?

Second: After I close br, can I use it to reference another BufferedReader and instantiate it in the same way with a different file?

Thanks for all help.

like image 577
Euclid Ye Avatar asked Feb 11 '26 16:02

Euclid Ye


2 Answers

Is this a good practice? I mean I embed FileReader as a parameter, so I may not be able to close it.

You don't need to close it. Closing the BufferedReader closes it.

And I suppose java may be smart enough to close it when br is closed?

Yes, see the Javadoc.

Second: After I close br, can I use it to reference another BufferedReader and instantiate it in the same way with a different file?

Yes.

like image 147
user207421 Avatar answered Feb 14 '26 04:02

user207421


And I suppose java may be smart enough to close it when br is closed?

Yes. The BufferedReader.close() Javadoc says (in part)

Closes the stream and releases any system resources associated with it.

The FileReader is a system resource associated with the BufferedReader in your question.

After I close br, can I use it to reference another BufferedReader and instantiate it in the same way with a different file?

Yes. As long as you call new BufferedReader.

like image 45
Elliott Frisch Avatar answered Feb 14 '26 04:02

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!