ITeye博客

Basic I/O

wutao8818 · 2009-06-30 23:00 · io · HTML · C · C++ · C# · SUN · Markdown

复习一下 IO

Byte Streams

http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html


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();
            }
        }
    }
}

2个小问题 1.Always Close Streams

finally块释放资源,为什么要判断 in != null ?

不是因为 in 对象可能前面自己释放了,而是因为发生异常的情况可能是2个文件可能发生一个打开一个不打开,或者2个都无法打开的情况,那么此时 in 仍然是 null ,并没有改变,所以需要判断。 in.close();是必须执行的部分,所以有必要放在finally块里,否则可能导致资源泄漏。

** 2.When Not to Use Byte Streams**

何时不使用byte流 byte流真的很底层,太底层的不健康。对于包含字符的数据,其实最好的实现是基于字符的流,但为什么这里需要讨论byte,因为所有的流都基于byte流 :shock:

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。