13. IO 流 
一.File 类的使用 
1.File 类的理解 
- File 类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
- File 类声明在java.io包下
- File 类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
- 后续 File 类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点"。
2.File 类的实例化 
2.1 常用构造器 
- File(String filePath)
- File(String parentPath,String childPath)
- File(File parentFile,String childPath)
2.2 路径的分类 
- 相对路径:相较于某个路径下,指明的路径
- 绝对路径:包含盘符在内的文件或文件目录的路径 说明: IDEA 中 如果大家开发使用JUnit中的单元测试方法测试,相对路径即为当前Module下。 如果大家开发使用main()测试,相对路径即为当前Project下。 Eclipse 中 不管使用单元测试方法还是使用main()测试,相对路径都是当前Project下
2.3 路径分隔符 
- windows和- DOS系统默认使用"- \"来表示
- UNIX和- URL使用"- /"来表示
3.File 类的常用方法 



二.IO 流概述 
1.流的分类 
- 操作数据单位:字节流、字符流
- 数据的流向:输入流、输出流
- 流的角色:节点流、处理流
图示:

2.流的体系结构 

3.重点说明的几个流结构 
| 抽象基类 | 节点流(或文件流) | 缓冲流(处理流的一种) | 
|---|---|---|
| InputStream | FileInputStream(read(byte[] buffer)) | BufferedInputStream(read(byte[] buffer)) | 
| OutputStream | FileOutputStream(write(byte[] buffer,0,len)) | BufferedOutputStream(write(byte[] buffer,0,len)) | 
| Reader | FileReader(read(char[] cbuf)) | BufferedReader(read(char[] cbuf)/readLine()) | 
| Writer | FileWriter(write(char[] cbuf,0,len)) | BufferedWriter(write(char[] cbuf,0,len)/flush()) | 
4.输入、输出的标准化过程 
4.1 输入过程 
- 创建File类的对象,指明读取的数据的来源。(要求此文件一定要存在)
- 创建相应的输入流,将File类的对象作为参数,传入流的构造器中
- 具体的读入过程: 创建相应的byte[]或char[]
- 关闭流资源
说明:程序中出现的异常需要使用try-catch-finlly处理
4.2 输出过程 
- 创建File类的对象,指明写出的数据的位置。(不要求此文件一定要存在)
- 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
- 具体的写出过程: write(char[]/byte[],0,len)
- 关闭流资源
说明:程序中出现的异常需要使用try-catch-finlly处理
三.节点流(或文件流) 
1.FileReader/FileWriter 的使用 
1.1 FileReader 的使用 
说明点:
- read()的理解:返回读入的一个字符。如果达到文件的末尾,返回-1
- 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
- 读入的文件一定要存在,否则就会报FileNotFoundException
java
@Test
public void testFileReader(){
    FileReader fr = null;
    try{
        // 1.实例化File类的对象,指明要操作的文件
        File file = new File("hello.txt"); // 相较于当前的Module
        // 2.提供具体的流
        fr = new FileReader(file);
        // 3.数据的读入
        // read(): 返回读入的一个字符。如果达到文件的末尾,返回-1
        char[] cubf = new char[5];
        int len;
        while((len = fr.read(cubf))!=-1){
            // 方式一:
            // 错误的写法
         //for(int i = 0;i< cubf.length;i++){
            //    System.out.println(cubf[i]);
            //}
            // 正确的写法
            for(int i = 0;i< len.length;i++){
                System.out.println(cubf[i]);
            }
            // 方式二:
            // 错误的写法,对应着方式一错误的写法
            // String str = new String(cubf);
            // 正确的写法
            String str = new String(cubf,0,len);
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(fr != null){
            try{
                // 资源的关闭
                fr.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}1.2 FileWriter 的使用 
从内存中写出数据到硬盘的文件里。
说明:
- 输出操作,对应的File可以不存在的。并不会报异常
- File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。- File对应的硬盘中的文件如果存在:- 如果流使用的构造器是:FileWriter(file,false)/FileWriter(file):对原文件的覆盖
- 如果流使用的构造器是:FileWriter(file,true):不会对原文件的覆盖,而是在原文件基础上追加内容
 
- 如果流使用的构造器是:
java
@Test
public void testFileWriter(){
    FileWriter fw = null;
    try{
        // 1.实例化File类的对象,指明写出的文件
        File file = new File("hello.txt");
        // 2.提供FileWriter的对象,用于数据的写出
        fw = new FileWriter(file,false);
        // 3.写出的操作
  fw.write("I have a dream!\n");
        fw.write("you need to have a dream!");
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(fw != null){
            try{
                // 资源的关闭
                fw.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}1.3 文本文件的复制 
java
@Test
public void testFileReaderFileWriter(){
    FileWriter fw = null;
    FileReader fr = null;
    try{
        // 1.实例化File类的对象,指明写出的文件
        File srcFile = new File("hello.txt");
        File descFile = new File("hello2.txt");
        // 不能使用字符流来处理图片等字节数据
        // File srcFile = new File("1.jpg");
        // File descFile = new File("2.jpg");
        // 2.创建输入流和输出流的对象
  fr = new FileReader(srcFile);
        fw = new FileWriter(descFile);
        // 3.数据的读入和写出操作
  char[] cubf = new char[5];
        int len;// 记录每次读入到cbuf数组中的字符的个数
        while(len = fr.read(cubf) != -1){
            // 每次写出len个字符
            fw.write(cubf,0,len);
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(fw != null){
            try{
                // 资源的关闭
                fw.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(fr != null){
            try{
                // 资源的关闭
                fr.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}2.FileInputStream/FileOutputStream 的使用 
- 对于文本文件(.txt,.java,.c,.cpp),用于字符流处理
- 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt),用于字节流处理
java
// 实现对图片的复制的操作
@Test
public void testFileInputOuputStream(){
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try{
        // 1.实例化File类的对象,指明写出的文件
        File srcFile = new File("1.jpg");
        File descFile = new File("2.jpg");
        // 2.创建输入流和输出流的对象
  fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(descFile);
        // 3.复制的过程
  byte[] buffer = new byte[5];
        int len;
        while(len = fis.read(buffer) != -1){
            // 每次写出len个字符
            fos.write(buffer,0,len);
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(fis != null){
            try{
                // 资源的关闭
                fis.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(fos != null){
            try{
                // 资源的关闭
                fos.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}四.缓冲流的使用 
1.缓冲流涉及到的类 
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
2.作用 
提高流的读取、写入的速度
提高读写速度的原因:内部提供了一个缓冲区。默认情况下是8kb
java
public class BufferedInputStream extends FilterInputStream{
    private static int DEFAULT_BUFFER_SIZE = 8192;
}3.典型代码 
3.1 使用 BufferedInputStream 和 BufferedOutputStream:处理非文本文件 
java
// 实现文件复制的方法
@Test
public void copyFileWithBuffered(String srcPath,String destPath){
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try{
        // 1.实例化File类的对象,指明写出的文件
        File srcFile = new File("1.jpg");
        File descFile = new File("2.jpg");
        // 2.造流
        // 2.1 造节点流
  FileInputStream fis = new FileInputStream((srcFile));
        FileOutputStream fos = new FileOutputStream((destPath));
        // 2.2 造缓冲流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);
        // 3.复制的细节:读取、写入
  byte[] buffer = new byte[1024];
        int len;
        while(len = bis.read(buffer) != -1){
            // 每次写出len个字符
            bos.write(buffer,0,len);
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(bis != null){
            try{
                // 资源的关闭
                bis.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(bos != null){
            try{
                // 资源的关闭
                bos.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}3.2 使用 BufferedReader 和 BufferedWriter:处理文本文件 
java
@Test
public void testBufferedReaderBufferWriter(){
    BufferedReader br = null;
    BufferedWriter bw = null;
    try{
        // 创建文件和相应的流
  br = new BufferedReader(new FileReader(new File("dbcp.txt")));
        bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
        // 读写操作
        // 方式一:使用char[]数组
  char[] cbuf = new char[1024];
        int len;
        while(len = br.read(buffer) != -1){
            // 每次写出len个字符
            bw.write(buffer,0,len);
            bw.flush();
        }
        // 方式二:使用String
  String data;
        while((data = br.readLine()) != -1){
            // 方式一
            // bw.write(data + "\n"); // data中不包含换行符
            // 方式二
            bw.write(data); // data中不包含换行符
            bw.newLine(); // 提供换行的操作
        }
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        if(bis != null){
            try{
                // 资源的关闭
                bis.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(bos != null){
            try{
                // 资源的关闭
                bos.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}五.转换流的使用 
1.转换流涉及到的类 
- InputStreamReader:将一个字节的输入流转换为字符的输入流- 解码:字节、字节数组 =>字符数组、字符串
 
- 解码:字节、字节数组 
- OutputStreamReader:将一个字符的输入流转换为字节的输出流- 编码:字符数组、字符串 =>字节、字节数组
 
- 编码:字符数组、字符串 
2.作用 
提供字节流与字符流之间的转换
3.图示 

4.典型实现 
java
@Test
public void test1() throws IOException{
    FileInputStream fis = new FileInputStream("dbcp.txt");
    // 参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集
    InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
    char[] cbuf = new char[20];
    int len;
    while((len = isr.read(cbuf)) != -1){
        String str = new String(cubf,0,len);
        System.out.println(str);
    }
    isr.close();
}
// 此时处理异常的话,仍然应该使用try-catch-finally
// 综合使用InputStreamReader和OutputStreamWriter
@Test
public void test2() throws IOException{
    // 1.造文件、造流
    File file1 = new File("dbcp.txt");
    File file2 = new File("dbcp_gbk.txt");
    FileInputStream fis = new FileInputStream(file1);
    FileOutputStream fos = new FileOutputStream(file2);
    InputStreamReader isr = new InputStreamReader(fis,"utf-8");
    OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
    // 2.读写过程
    char[] cbuf = new char[20];
    int len;
    while((len = isr.read(cbuf)) != -1){
       osw.write(cubf,0,len);
    }
    // 3.关闭资源
    isr.close();
    osw.close();
}5.说明 
文件编码的方式(比如:GBK),决定了解析时使用的字符集(也只能是GBK)。
六.其他流的使用 
1.标准的输入输出流 
- System.in:标准的输入流,默认从键盘输入
- System.out:标准的输出流,默认从控制台输出
修改默认的输入和输出行为:
System类的setIn(InputStream is)/setOut(PrintStream ps)方式重新指定输入和输出的流。
2.打印流 
- PrintStream
- PrintWriter
说明:
- 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
- System.out返回的是- PrintStream的实例
3.数据流 
用于读取或写出基本数据类型的变量或字符串
java
// 练习:将内存中的字符串、基本数据类型的变量写出到文件中
// 注意:处理异常的话,仍然应该使用try-catch-finally
@Test
public void test3() throws IOException{
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
    dos.wrintUTF("hello");
    dos.flush();// 刷新操作,将内存中的数据写入文件
    dos.wrintInt(23);
    dos.flush();
    dos.wrintBoolean(false);
    dos.flush();
    dos.close();
}
// 将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中
// 注意点:读取不同数据类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致
@Test
public void test4() throws IOException{
    DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
    String name = dos.wrintUTF();
    int age = dos.wrintInt();
    Boolean bol =  dos.wrintBoolean();
    dos.close();
}