流(stream)的理解

我曾一度对流的概念管不清楚--什么输入流、输出流、read和write等等。

而现在重新去理解这个概念的时候,发现其实并没有我以前想象那么复杂。

流:

程序和外部设备进行数据传输的一个通道。分为输入流和输出流。

输入流(InputStream):

终端设备里的数据传输给程序的通道

输出流(OutStream)

程序的数据传输给终端设备的通道

外部设备:

文件、键盘、鼠标、屏幕、控制台。。。(有些外部设备只能有输入流或者输出流)

Read:

输入流通过read把外部设备的数据读到程序中

Write:

输出流通过write吧程序中的数据写到外部设备

 

流程:

外部设备--->>>输入流--->>> 程序 --->>>输出流 --->>>外部设备

 

举例(java):

场景:通过程序实现文件的复制,并在复制的文件中加入一些信息。

程序:

public class CopyFile {
    public byte[] getFile() throws IOException {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("c:\\file.txt");
            byte[] result = new byte[fileInputStream.available()];
            fileInputStream.read(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }

        }

        return null;
    }

    public void copyFile(byte[] result) throws IOException {
        FileOutputStream fileOutputStream = null;
        try {
            File newFile = new File("c:\\copyFile.txt");
            fileOutputStream = new FileOutputStream(newFile);
            fileOutputStream.write(result);
            fileOutputStream.write("复制成功了".getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }

    }

    public static void main(String[] args) {
        CopyFile copyFile = new CopyFile();
        byte[] result;
        try {
            result = copyFile.getFile();
            copyFile.copyFile(result);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        

    }
}

 

分析:

1:通过FileInputStream给文件创建一个输入流通道

2:通过FileInputStream的read方法,把文件信息读取到程序中

3:通过File来创建一个副本文件

4:通过FileOutputStream给副本文件创建一个输出流通道

5:通过FileOutputStream的write方法,给副本文件写入信息。

总结:

通过输入流能把外部设备中的数据读到程序里面

而通过输出流能把程序中的数据写入外部设备中。

 

posted @ 2013-04-25 11:45  小虾Joe  阅读(1778)  评论(7编辑  收藏  举报