我正在使用以下代码从连接到服务器关闭InputStream和OutputStream:
try {
if (mInputStream != null) {
mInputStream.close();
mInputStream = null;
}
if (mOutputStream != null) {
mOutputStream.close();
mOutputStream = null;
}
} catch (IOException e) {
e.printStackTrace();
}
然而,溪流没有关闭,它们仍然活着。如果我再次连接,则有两个不同的InputStream。 catch
部分没有例外。
我做错了什么?
答案 0 :(得分:18)
您发布的代码有两个问题:
你想要更像这样的东西:
InputStream mInputStream = null;
OutputStream mOutputStream = null;
try {
mInputStream = new FileInputStream("\\Path\\MyFileName1.txt");
mOutputStream = new FileOutputStream("\\Path\\MyFileName2.txt");
//... do stuff to your streams
}
catch(FileNotFoundException fnex) {
//Handle the error... but the streams are still open!
}
finally {
//close input
if (mInputStream != null) {
try {
mInputStream.close();
}
catch(IOException ioex) {
//Very bad things just happened... handle it
}
}
//Close output
if (mOutputStream != null) {
try {
mOutputStream.close();
}
catch(IOException ioex) {
//Very bad things just happened... handle it
}
}
}