简体   繁体   中英

Why doesn't `loadFont` close input stream? Should I close it?

Looking at the documentation of Font#loadFont I came across this remark:

This method does not close the input stream.

Unfortunately, this is not explained or expanded upon. So my question is:

  1. What are possible reasons the API won't close the input stream? Is it likely you would like to re-use the stream? I mostly use this method like this:

     Font.loadFont(getClass().getResourceAsStream("path/to/font"), 13.0); 

    to make sure the font is available for my application, so I never re-use the input stream, and I can't really think of a reason I'd want to.

  2. Should I close the input stream myself? Should I expect any problems if I'm not closing the input stream? In the past I've had problems with a font loaded this way, where some labels configured with this font started showing squares, while others (on the same scene!) kept working fine. Could this be related to not closing the input stream?

The documentation for every API involving scarce or external resources (such as file descriptors or streams) will make it clear whose responsibility it is to clean up (in this case, close the stream). This is sometimes referred to as "ownership".

In this case the documentation states that the loadFont method does not take ownership of the stream. Therefore it still belongs to you: It is your responsibility to close the stream.

The try-with-resources statement is the best way to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM