简体   繁体   English

关闭InputStream

[英]Closing an InputStream

I have an InputStream that gets passed to an InputSource: 我有一个InputStream传递给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? 如何正确关闭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. 我得到一个java.lang.NullPointerException,因为流在​​“ xmlSource”完成之前被关闭了。 Also the object "xmlTableRowLoader" extends Thread. 同样,对象“ xmlTableRowLoader”扩展了线程。

That depends on how AcmTableRowLoader is using it. 这取决于AcmTableRowLoader的使用方式。 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. 但是,由于似乎AcmTableRowLoader在构造函数之外的其他地方使用它,所以我建议让AcmTableRowLoader创建并关闭流本身,因为它知道何时完成处理。

Or in short, close it after you have closed the xmlSource. 或者简而言之,在关闭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. 尝试关闭从其读取的线程中的Stream,当parse()返回时,可以关闭该流。 If you want to close the stream in another Thread you can have a look at AsyncTask. 如果要在另一个线程中关闭流,可以查看AsyncTask。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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