JAVA io流

流的概念和作用

流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。

一.IO流中的结构

Java流操作有关的类或接口:

JAVA io流

Java流类图结构:

JAVA io流

  • 字符流:顾名思义,该流只能处理字符,但处理字符速度很快
  • 字节流:可以处理所有以bit为单位储存的文件,也就是说可以处理所有的文件,但是在处理字符上的速度不如字符

输入字节流 InputStream

  • InputStream 是所有的输入字节流的父类,它是一个抽象类。
  • ByteArrayInputStreamStringBufferInputStreamFileInputStream 是三种基本的介质流,它们分别从Byte 数组StringBuffer、和本地文件中读取数据。
  • PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped 相关的知识后续单独介绍。
  • ObjectInputStream 和所有FilterInputStream 的子类都是装饰流(装饰器模式的主角)。

输出字节流 OutputStream

  • OutputStream 是所有的输出字节流的父类,它是一个抽象类。
  • ByteArrayOutputStreamFileOutputStream 是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。
  • PipedOutputStream 是向与其它线程共用的管道中写入数据。
  • ObjectOutputStream 和所有FilterOutputStream 的子类都是装饰流。

总结:

  • 输入流:InputStream或者Reader:从文件中读到程序中;
  • 输出流:OutputStream或者Writer:从程序中输出到文件中;

节点流

节点流:直接与数据源相连,读入或读出。
直接使用节点流,读写不方便,为了更快的读写文件,才有了处理流。
JAVA io流

常用的节点流

  • 父 类 :InputStream 、OutputStream、 Reader、 Writer
  • 文 件 :FileInputStream 、 FileOutputStrean 、FileReader 、FileWriter 文件进行处理的节点流
  • 数 组 :ByteArrayInputStream、 ByteArrayOutputStream、 CharArrayReader 、CharArrayWriter 对数组进行处理的节点流(对应的不再是文件,而是内存中的一个数组)
  • 字符串 :StringReader、 StringWriter 对字符串进行处理的节点流
  • 管 道 :PipedInputStream 、PipedOutputStream 、PipedReader 、PipedWriter 对管道进行处理的节点流

处理流

处理流和节点流一块使用,在节点流的基础上,再套接一层,套接在节点流上的就是处理流。如BufferedReader.处理流的构造方法总是要带一个其他的流对象做参数。一个流对象经过其他流的多次包装,称为流的链接。
JAVA io流

常用的处理流

  • 缓冲流:BufferedInputStrean 、BufferedOutputStream、 BufferedReader、 BufferedWriter 增加缓冲功能,避免频繁读写硬盘。
  • 转换流:InputStreamReader 、OutputStreamReader实现字节流和字符流之间的转换。
  • 数据流: DataInputStream 、DataOutputStream 等-提供将基础数据类型写入到文件中,或者读取出来。

转换流

InputStreamReader 、OutputStreamWriter InputStreamOutputStream作为参数,实现从字节流到字符流的转换。

构造函数

InputStreamReader(InputStream);        //通过构造函数初始化,使用的是本系统默认的编码表GBK。
InputStreamWriter(InputStream,String charSet);   //通过该构造函数初始化,可以指定编码表。
OutputStreamWriter(OutputStream);      //通过该构造函数初始化,使用的是本系统默认的编码表GBK。
OutputStreamwriter(OutputStream,String charSet);   //通过该构造函数初始化,可以指定编码表。

带缓冲区的流中的特殊方法

* readLine()属于BufferedReader

* newLine()属于BufferedWriter

newLine 和 \r\n的区别

* newLine是跨平台的方法

* \r\n只支持的是windows系统

案例 FileInputStream类的使用

package com.io;

import java.io.*;

/**
 * User: 1421718760
 * Date: 2019/4/16 0016
 * Time: 15:41
 * Description: 读取文件
 * 1.根据path路径实例化一个输入流的对象
 * 2.通过构造函数初始化 处理流,系统默认的编码表GBK
 * 3.转换成 缓冲流
 * 4.从缓冲流中写入数据
 * 5.关闭
 */
public class FileInput {

    public static void main(String[] args) {
        String file = "C:/Users/P0114255/Desktop/mysql.txt";
        String reslut = readTxt(file);
        System.out.println(reslut);
    }

    //	读取文件
    public static String readTxt(String path){
        InputStream is = null;
        String str = "";
        StringBuilder strb = new StringBuilder("");
        try {
            // 根据path路径实例化一个输入流的对象
            is = new FileInputStream(new File(path));

            /**
             * 方法 1
             */
            /*//通过构造函数初始化处理流,系统默认的编码表GBK
            InputStreamReader isr = new InputStreamReader(is, getCode(path));
            //缓冲流
            BufferedReader br = new BufferedReader(isr);
            while (null != (str = br.readLine())) {
                strb.append(str);
                strb.append("\r\n");
            }
            br.close();*/
            /**
             * 方法2
             */
            //2. 返回这个输入流中可以被读的剩下的bytes字节的估计值;
            int size =  is.available() ;
            //3. 根据输入流中的字节数创建byte数组;
            byte[] array = new byte[size];
            //4.把数据读取到数组中;
            is.read( array ) ;
            //5.根据获取到的Byte数组新建一个字符串,然后输出;
            strb.append(new String(array));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if ( is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return strb.toString();
    }

    /**
     *  获取编码格式 gb2312,UTF-16,UTF-8,Unicode,UTF-8
     */
    public static String getCode(String path) {
      try {
          InputStream inputStream = new FileInputStream(path);
          byte[] head = new byte[3];
          inputStream.read(head);
          String code = "gb2312"; // 或GBK
          if (head[0] == -1 && head[1] == -2)
              code = "UTF-16";
          else if (head[0] == -2 && head[1] == -1)
              code = "Unicode";
          else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
              code = "UTF-8";
          inputStream.close();
          return code;
      }catch (Exception e){
          e.printStackTrace();
          return null;
      }
    }


}

案例 FileOutputStream 类的使用

package com.io;

import java.io.*;

/**
 * User: 1421718760
 * Date: 2019/4/16 0016
 * Time: 16:09
 * Description: 写入文件
 */
public class FileOutput {
    public static void main(String[] args) {
        String file = "C:/Users/P0114255/Desktop/fileOut.txt";
        String findOut = "aaaaaa似睡非睡大 #¥%。、\n\rvvv";
        writeFile(file,findOut);

    }

    public static void writeFile(String fileOutput,String findOut){
        FileOutputStream  is = null;
        try {
            File file = new File(fileOutput);
            File fileParent = file.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdir();
            }
            file.createNewFile();
            //1、根据文件路径创建输出流
            is = new FileOutputStream (fileOutput);

            /**
             * 1
             */
            //2、把string转换为byte数组;
            byte[] array = findOut.getBytes() ;
            //3、把byte数组输出;
            is.write( array );
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if ( is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

文件A复制到文件B

package com.io;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * User: 1421718760
 * Date: 2019/4/16 0016
 * Time: 17:46
 * Description: 复制文件
 */
public class fileCopy {
    public static void main(String[] args) {
        String path1 = "C:/Users/P0114255/Desktop/1.pdf";
        String path2 = "C:/Users/P0114255/Desktop/2.pdf";
        copyFile(path1,path2);
    }
    public static void copyFile(String path1,String path2){
        try {
            File fil1 = new File(path1);
            File fil2 = new File(path2);
            File fileParent = fil2.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdir();
            }
            fil2.createNewFile();

            FileInputStream fi = new FileInputStream(fil1);
            //一个叫输入流的桶,装满了一桶叫做D:/111.pdf文件的水
            FileOutputStream fs = new FileOutputStream(fil2);
            //一个叫输出流的空桶,但想装满叫做"D:/222.pdf"文件的水

            byte[] buf = new byte[521];
            //叫做buf的水瓢
            int len = -1;
            //用来测量每次水瓢装了多少水
            while((len = fi.read(buf)) != -1){
                //一次次的用水瓢在输入流的桶里舀水,并用len测了舀了多少水,当len等于-1意味着水舀光了,该结束舀水了。
                fs.write(buf, 0, len);
                //一次次把水瓢里的水放到了输出流的桶里
            }
            fs.flush();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java中io流的学习(一)File:https://blog.****.net/qq_41061437/article/details/81672859

Java中io流的学习(二)FileInputStream和FileOutputStream:https://blog.****.net/qq_41061437/article/details/81742175

Java中io流的学习(三)BuffereInputStream和BuffereOutputStream:https://blog.****.net/qq_41061437/article/details/81743522

Java中io流的学习(四)InputStreamReader和OutputStreamWriter:https://blog.****.net/qq_41061437/article/details/81745300

Java中io流的学习(五)FileReader和FileWriter:https://blog.****.net/qq_41061437/article/details/81747105

 

Java中io流的学习(六)BufferedReader和BufferedWriter:https://blog.****.net/qq_41061437/article/details/81747323

Java中io流的学习(七)ObjectInputStream和ObjectOutputStream:https://blog.****.net/qq_41061437/article/details/81748461

Java中io流的学习(八)PrintStream和PrintWriter:https://blog.****.net/qq_41061437/article/details/81782770

Java中io流的学习(九)RandomAccessFile:https://blog.****.net/qq_41061437/article/details/81805351

Java中io流的学习(十)ByteArrayInoutStream和ByteArrayOutputStream:https://blog.****.net/qq_41061437/article/details/81806245

Java中io流的学习(十一)NIO:https://blog.****.net/qq_41061437/article/details/81809370

Java中io流的学习(总结):https://blog.****.net/qq_41061437/article/details/81740680