Java IO tips
2011-02-23 16:38 RayLee 阅读(279) 评论(0) 收藏 举报Java IO操作最常犯的错误是忘记关闭所操作的Stream。这些Stream是跟操作系统的资源(如文件,网络)联系在一起的,而操作系统的资源是有限的,如果不能正确释放,会导致其它程序不能正常工作。
是不是所有的Stream都需要调用close()方法释放资源?与文件,网络相关的Stream应该调用close()。byte array streams可以不用。
try {
OutputStream out = new FileOutputStream("numbers.dat");
// Write to the stream...
out.close( );
}
catch (IOException ex) {
System.err.println(ex);
}
上面代码的问题:如果抛出异常,该文件Stream不会关闭。
利用try-catch-finally解决:
// Initialize this to null to keep the compiler from complaining
// about uninitialized variables
OutputStream out = null;
try {
out = new FileOutputStream("numbers.dat");
// Write to the stream...
}
catch (IOException ex) {
System.err.println(ex);
}
finally {
if (out != null) {
try {
out.close( );
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
无论是否抛出异常,该文件Stream都会关闭,系统资源得到释放。
如果你不想处理异常,而打算让调用代码处理。你在定义方法的时候声明抛出IOException。上述代码可以简化为:
// Initialize this to null to keep the compiler from complaining
// about uninitialized variables
OutputStream out == null;
try {
out = new FileOutputStream("numbers.dat");
// Write to the stream...
}
finally {
if (out != null) out.close( );
}
浙公网安备 33010602011771号