IO流

来源:互联网 发布:淘宝网充气沙发 编辑:程序博客网 时间:2024/06/05 02:26
    IO分别代表输入(Input)和输出.判断是输入还是输出是站在内存的角度上,数据从磁盘上流入内存被看做是Input,输出从内从中写到磁盘上被看做是Output。
    IO流分为字节流、字符流和转换流。
    字节流指的是在操作的时候都是二进制文件(视频文件,音频文件,文档文件----只要是使用文本编辑器打开不能正常使用的文件基本上都可以判定为是字节文件)
    字符流指在进行IO操作的时候是文本文件,例如txt,.java,.html等等。可以使用文本编辑器打开并正常使用的文件通常为文本文件。
   转换流的存在就是为了在字节流和字符流之间转换。
   常见的字节流:
    InputStream(抽象类)      此抽象类是表示字节输入流的所有类的超类
    OutputStream(抽象类)     次抽象类是表示字节输出流的所有类的超类
    FileInputStream:  文件输入流
    FileOutputStream:  文件输出流
    由于InputStream和OutputStream是抽象类,因此不能实例化,只能使用更具体的子类FileInputStream类和FileOutputStream类。这两个类在对文件进行读写操作时,是配合使用的。

    example:

try {                FileInputStream fis = new FileInputStream("D:/1.jpg");FileOutputStream fos = new FileOutputStream("D:/2.jpg");int len = -1;while((len = fis.read()) != -1){fos.write(len);}fis.close();fos.flush();fos.close();} catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();}
    由于代码要抛出强制捕获型异常,因此需要使用try...catch块处理一下。

    但是在实际执行的时候这种方式效率是很低的,大家在这样进行拷贝的时候可以使用System.currentTimeMIlis这样的类进行计算一下拷贝文件所需的时间。由于这种拷贝速度非常慢。因此我们就需要使用缓冲机制。

 example:

    

try {FileInputStream fis = new FileInputStream("D:/1.jpg");FileOutputStream fos = new FileOutputStream("D:/2.jpg");BufferedInputStream bis = new BufferedInputStream(fis);BufferedOutputStream bos = new BufferedOutputStream(fos);int len = -1;while((len = bis.read()) != -1){bos.write(len);}bis.close();bos.flush();bos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
    增加了缓冲功能后,文件拷贝速率明显提升,在这里也介绍下一种设计模式-装饰者模式(对象本身不具备某种功能,但是经过层层嵌套就可以具有某种额外的功能)

    相比大家都知道我在说什么了,就是这段程序:

    

        BufferedInputStream bis = new BufferedInputStream(fis);        BufferedOutputStream bos = new BufferedOutputStream(fos);


0 0
原创粉丝点击