简体   繁体   中英

Closing an InputStream

I have an InputStream that gets passed to an InputSource:

int resID = getResources().getIdentifier("c" + getCfrFile(), "raw", getPackageName());  
InputStream ins  = getResources().openRawResource(resID); 
InputSource xmlSource = new InputSource(ins);   

xmlTableRowLoader = new AcmTableRowLoader(handler, xmlSource, this, pathBuilder(false), "title");

How do I properly close() the InputStream? When I try to close it:

ins.Close();

I get an java.lang.NullPointerException because the stream gets closed before the "xmlSource" is finished with it. Also the object "xmlTableRowLoader" extends Thread.

That depends on how AcmTableRowLoader is using it. If it is only using it in its constructor, which I doubt from what you said, then closing it in the method above might be valid. However, since it appears that AcmTableRowLoader is using it in places other than the constructor... I would suggest having the AcmTableRowLoader create and close the stream itself since it knows when it is done with it.

Or in short, close it after you have closed the xmlSource. Hard to tell exactly where / how without more context. Looks like you just jumped the gun.

Try to close the Stream in the Thread that reads from it, when parse() returns the stream can be closed. If you want to close the stream in another Thread you can have a look at AsyncTask.

最佳做法是将整个代码放入try{ ... }catch块中,并在您应关闭输入流的位置添加一个finally块。

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