Basic I/O

复习一下 IO

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:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值