复习一下 IO
Byte Streams
[url]http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html[/url]
[img]http://java.sun.com/docs/books/tutorial/figures/essential/byteStream.png[/img]
[b]2个小问题[/b]
[b]1.Always Close Streams[/b]
finally块释放资源,为什么要判断 in != null ?
不是因为 in 对象可能前面自己释放了,而是因为发生异常的情况可能是2个文件可能发生一个打开一个不打开,或者2个都无法打开的情况,那么此时 in 仍然是 null ,并没有改变,所以需要判断。
in.close();是必须执行的部分,所以有必要放在finally块里,否则可能导致资源泄漏。
[b]
2.When Not to Use Byte Streams[/b]
何时不使用byte流
byte流真的很底层,太底层的不健康。对于包含字符的数据,其实最好的实现是基于字符的流,但为什么这里需要讨论byte,因为所有的流都基于byte流 :shock:
Byte Streams
[url]http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html[/url]
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
[img]http://java.sun.com/docs/books/tutorial/figures/essential/byteStream.png[/img]
[b]2个小问题[/b]
[b]1.Always Close Streams[/b]
finally块释放资源,为什么要判断 in != null ?
不是因为 in 对象可能前面自己释放了,而是因为发生异常的情况可能是2个文件可能发生一个打开一个不打开,或者2个都无法打开的情况,那么此时 in 仍然是 null ,并没有改变,所以需要判断。
in.close();是必须执行的部分,所以有必要放在finally块里,否则可能导致资源泄漏。
[b]
2.When Not to Use Byte Streams[/b]
何时不使用byte流
byte流真的很底层,太底层的不健康。对于包含字符的数据,其实最好的实现是基于字符的流,但为什么这里需要讨论byte,因为所有的流都基于byte流 :shock: