java io读书笔记(7) Closing Output Streams
2013-07-16 10:44
183 查看
输出完毕后,需要close这个stream,从而使操作系统释放相关的资源。举例:
public void close( ) throws IOException
并不是所有的stream都需要close,可是,诸如file或者network,打开后,需要关闭。
However, this code fragment has a potential leak. If an IOException is thrown while writing, the stream won't be closed. It's more reliable to close the stream in a finally block so that it's closed whether or not an exception is thrown. To do this you need to declare the OutputStream variable outside the try block. For example:
public void close( ) throws IOException
并不是所有的stream都需要close,可是,诸如file或者network,打开后,需要关闭。
try { OutputStream out = new FileOutputStream("numbers.dat"); // Write to the stream... out.close( ); } catch (IOException ex) { System.err.println(ex); }
However, this code fragment has a potential leak. If an IOException is thrown while writing, the stream won't be closed. It's more reliable to close the stream in a finally block so that it's closed whether or not an exception is thrown. To do this you need to declare the OutputStream variable outside the try block. For example:
// 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); } } }
相关文章推荐
- Standard input, output, and error streams
- spark streaming 异常No output streams registered, so nothing to execute
- Output Operations on DStreams
- spark-streaming-[7]-Output Operations on DStreams-foreachRDD写Mysql
- java io读书笔记(5) Writing Bytes to Output Streams
- Angular 2 中的 Output和Input的使用
- Java Streams,第 1 部分: java.util.stream 库简介
- Session 0x0 for server hostname/***.***.***.***:2181, unexpected error, closing socket connection an
- PLSQL UTL_FILE output file
- 基于Akka-Streams的HTTP代理的实现
- Qt Creator报错:Cannot retrieve debugging output
- Java 8 中的 Streams API 详解
- android应用私有存储文件的写入与读取-openFileInput 和 openFileOutput
- logstash_output_mongodb插件用途及安装详解
- [Language]File Input and Output
- python3 获得shell的输出内容(subprocess.getstatusoutput)
- C++——流的文件I/O(Input & Output)
- Checking standard output of PBS jobs in real time
- SQL 语句中output参数的使用 很实用!
- Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect