---
title: "Basic I/O"
author: "wutao8818"
date: "2009-06-30T23:00:23Z"
tags: ["C", "C#", "C++", "HTML", "SUN"]
slug: "basic-i-o"
draft: false
lastmod: "2009-06-30T23:01:47Z"
id: 417900
url: "https://wutaoo.iteye.com/blog/417900"
---

复习一下 IO

Byte Streams

<http://java.sun.com/docs/books/tutorial/essential/io/bytestreams.html>


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

```


![](http://java.sun.com/docs/books/tutorial/figures/essential/byteStream.png)

**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: