• I/O浅析


    1.为什么需要I/O?

    因为程序需要从别的文件中获取内容或者程序要将自身的内容传入到文件中。

    2.流种类的概述

    1.字节流和字符流

      字节流的基础单位是byte                  字符流的基础单位是char

    2.InputStream和OutputStream

    InputStream:外部文件内容输入到程序           OutputStream:程序内容输出到外部文件

    3.基础流:各种扩展的InputStream和OutputStream流

      每种扩展的形式分别处理不同的文件 (不一一展开,到后面详解一种)

    4.处理流:安装在基础流上的流

       以InputStream和OuputStream为基础,对I/O进行装饰。(就像在基础管道上套了一层管道,然后有了新的功能)。(不展开,后面详解最主要用到的)

    3.流的主要方法和运行原理(主讲InputStream/OutputStream Reader和Writer原理一致)

    InputStream:

    public abstract int read()
                      throws IOException
    //运行原理:每访问一次指针下移一字节,int返回该自己的int类型(0-255),当到达文件末尾时候返回-1
    public int read(byte[] b)
             throws IOException
    //运行原理,将读取到的自己存入byte[] b中(b存满为止),然后指针下移到b存满的位置,int返回多少字节存入byte[]中,若到达文件末尾返回-1

    OutputStream:

    public int write(byte[] b)
                throws IOException
    //运行原理:将byte[] b中的字节输出到外部文件。


    4.基础流讲解(FileInputStream和FileOutputStream)

    1.基础知识File类

      作用:获取文件的句柄,并可获取文件的相关信息

      创建:File file = new File(String path);

    2.FileInputStream和FileOutputStream的创建

      FileInputStream is = new FileInputStream(File file);   FileInputStream os = new FileOutputStream(File file);

      所以:基础流是用来:获取不同文件的inputStream和outputStream。

    3.处理流:BufferedInputStream

      1.原理

         作用:将从InputStream获得的字节,放入到一个32字节的缓冲区中,能够让获取的字节按照每一行输出且以String形式。

         问题:如果缓冲区没满,不会将缓存到其中的字节输出。

      2.使用

    InputStream is = new InputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    //在InputStream上套了一层
    String builder = new String buidler(); //具有缓冲性质的String类型
    while((String s = bis.readLine()) != null){  //readLine() 返回 String类型,若到达文件尾部返回Null
            builder.append(s);
            bis.flush()  //将缓存中的字节强制输出
    }    
  • 相关阅读:
    supervisor 配置
    单链表
    二叉排序树
    python 排序
    64 位 Ubuntu 下 android adb 不可用解决方法
    python 获取文件夹大小
    Ubuntu mongodb 安装和配置
    关于c3p0配置详细说明
    dwr消息推送
    关于如果修改 ie 浏览器 文本模式
  • 原文地址:https://www.cnblogs.com/rookiechen/p/5232490.html
Copyright © 2020-2023  润新知