WELCOME

任何一个伟大的目标,都有一个微不足道的开始。

韩顺平老师讲解IO流

韩顺平老师-IO流

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QrW2SZI1-1675570276056)(photo/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L25pbmdtZW5nc2h1eGlhd28=,size_16,color_FFFFFF,t_70.png)]

1. 文件

1.1 什么是文件

文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文件,excel文件…都是文件。它既可以保存一张图片,也可以保持视频,声音

1.2 文件流

文件在程序中是以流的形式操作的。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AiE8KbJF-1675570276058)(photo/image-20230204163804279.png)]

2. 常用的文件操作

2.1 创建文件对象相关构造器和方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hqlaSfMt-1675570276058)(photo/image-20230204175719422.png)]

  • 应用实例演示 FileCreate.java
    • 在d盘下,创建文件new1.txt,new2.txt,new3.txt,用三种方式
package com.yujianedu.file;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * 演示创建文件
 */
public class FileCreate {
    public static void main(String[] args) {

    }

    //方式1 new File(String pathname)
    @Test
    public void createFile01(){
        String filePath = "D:\\new1.txt";
        File file01 = new File(filePath);

        try {
            file01.createNewFile();
            System.out.println("文件创建成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//方式2 new File(File parent,String child) //根据父目录文件+子路径构建
//e:\\news2.txt
@Test
public void createFile02(){
    File parentPath = new File("d:\\");
    String filename = "new2.txt";
    //这里的file对象,在java程序中,只是一个对象
    //只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
    File file02 = new File(parentPath,filename);

    try {
        file02.createNewFile();
        System.out.println("文件创建成功!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
//方式 3 new File(String parent,String child) //根据父目录+子路径构建
@Test
public void createFile03(){
    String parentPath = "d:\\";
    String filename = "new3.txt";
    //这里的file对象,在java程序中,只是一个对象
    //只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
    File file03 = new File(parentPath,filename);

    try {
        file03.createNewFile();
        System.out.println("文件创建成功!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

2.2 获取文件的相关信息

getName,getAbsolutePath,getParent,length,exists,isFile,isDirectory

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IlwPlitx-1675570276059)(photo/image-20230204182535600.png)]

2.3应用案例演示 FileInformation.java

如何获取到文件的大小.文件名.路径.父路径,是文件还是目录,(目录本质也是文件,一种特殊的文件),是否存在.

package com.yujianedu.file;

import org.junit.Test;

import java.io.File;

public class FileInfomation {
    public static void main(String[] args) {

    }
    @Test
    public void info(){
        File file = new File("d:\\new1.txt");
        System.out.println("文件名字" + file.getName());
        System.out.println("文件绝对路径" + file.getAbsolutePath());
        System.out.println("文件父路径" + file.getParent());
        System.out.println("文件大小" + file.length());
        System.out.println("文件是否存在" + file.exists());
        System.out.println("是否是一个文件" + file.isFile());
        System.out.println("是否是一个目录" + file.isDirectory());
    }
}

执行结果:

文件名字new1.txt
文件绝对路径d:\new1.txt
文件父路径d:\
文件大小12
文件是否存在true
是否是一个文件true
是否是一个目录false

2.4 目录的操作和文件删除

mkdir创建一级目录、mkdirs创建多级目录、delete删除空目录或文件

> [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lhGogeQV-1675570276060)(photo/image-20230204185229360.png)]

2.5 应用案例演示

1)判断 d:\news1.txt 是否存在,如果存在就删除

@Test
public void m1(){
    String filename = "D:\\new1.txt";
    File file = new File(filename);

    if(file.exists()){
        if (file.delete()){
            System.out.println(filename + "删除文件成功");
        }else {
            System.out.println(filename + "删除文件失败");
        }
    }else {
        System.out.println("文件不存在...");
    }
}

执行结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0FAFCkrG-1675570276060)(photo/image-20230204185350565.png)]

2)判断 D:\demo02是否存在,存在就删除,否则提示不存在。

// 判断 D:\\demo02是否存在,存在就删除,否则提示不存在。
@Test
public void m2(){
    String directory = "D:\\demo02";
    File file = new File(directory);

    if(file.exists()){
        file.delete();
    }else {
        System.out.println("文件不存在...");
    }
}

执行结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H5TQ3T9f-1675570276062)(photo/image-20230204185833101.png)]

3)判断 D:\demo\a\b\c 目录是否存在,如果存在就提示已经存在,否则就创建

//判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
@Test
public void m3(){
    String directory = "D:\\demo\\a\\b\\c";
    File file = new File(directory);

    if(file.exists()){
        System.out.println(directory + "已存在");
    }else {
        if(file.mkdirs()){
            System.out.println(directory + "创建成功");
        }else {
            System.out.println("创建失败");
        }
    }
}

执行结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dbpUdOsx-1675570276062)(photo/image-20230204185904069.png)]

3. IO 流原理及流的分类

3.1 Java IO 流原理

  1. I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。
    如读/写文件,网络通讯等。
  2. Java程序中,对于数据的输入/输出操作以”流(stream)"的方式进行。
  3. java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
  4. 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
  5. 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FlkX2dpm-1675570276062)(photo/image-20230204190504444.png)]

3.2 流的分类

  • 按操作数据单位不同分为:字节流(8bit)二进制文件,字符流(按字符)文本文件
  • 按数据流的流向不同分为:输入流,输出流
  • 按流的角色的不同分为:节点流,处理流/包装流

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-snDyyITV-1675570276063)(photo/image-20230204190534746.png)]

1)Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。

2)由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

4. IO 流体系图-常用的类

  1. IO 流体系图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YE369tQC-1675570276064)(photo/image-20230204191021534.png)]

  1. 文件 VS 流

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-abK3sveY-1675570276065)(photo/image-20230204231619422.png)]

4.1 FileInputStream 介绍

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zebtoxfN-1675570276065)(photo/image-20230204232913432.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lm1RCnVB-1675570276066)(photo/image-20230204233001135.png)]

4.2 FileInputStream 应用实例 FileInputStream_.java

要求: 请使用 FileInputStream 读取 hello.txt 文件,并将文件内容显示到控制台

使用 FileInputStream 有 2 种方式进行读取,分别是read(),read(byte[] b),第一种不带参数的就是一个字节一个字节的读取,第二种就是可以读取多个字节(根据你设置的数组长度决定)

  • 第一种通过read 读取hello.txt
/**
     * 演示读取文件... * 单个字节的读取,效率比较低
     * -> 使用 read()
     */
@Test
public void readFile01(){
    String filePath = "D:\\hello.txt";
    int readData = 0;
    /* 为什么要先在这里定义 fileInputStream 文件输入流,因为你在最后需要释放这个资源,
        假如你没有扩大 fileInputStream 的作用范围,让它的作用范围在try中,在最后面无法将 fileInputStream 释放掉
         */
    FileInputStream fileInputStream = null;
    try {
        // 创建FileInputStream对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
        //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止。
        //如果返回-1,表示读取完毕
        while ((readData=fileInputStream.read()) != -1){
            System.out.print((char) readData); //转化成char显示
        }
    }catch (IOException e) {
        e.printStackTrace();
    }finally {
        //关闭文件流,释放资源
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 第二种通过read(byte[] b) 读取hello.txt
/**
     * 使用 read(byte[] b) 读取文件,提高效率
     */
@Test
public void readFile012(){
    String filePath = "D:\\hello.txt";
    FileInputStream fileInputStream = null;
    //直接数组
    byte[] buf = new byte[8]; //一次性读取8个
    int buflen = 0;
    try {
        // 创建FileInputStream对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
        //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止。
        //如果返回-1,表示读取完毕
        //如果读取正常,则返回实际读取的字节数
        /*
                意思就是因为你buf最多可以读取8个字节,但是当你最后读取的时候不足8个字节的时候,
                它读取的直接就是你当前所剩下的字节
             */
        while ((buflen=fileInputStream.read(buf)) != -1){ //fileInputStream.read(buf) 返回值就是读取读取的字节数
            System.out.print(new String(buf,0,buflen)); //转化成char显示
        }
    }catch (IOException e) {
        e.printStackTrace();
    }finally {
        //关闭文件流,释放资源
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4.3 FileOutputStream 介绍

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5NDtigb8-1675570276067)(photo/image-20230205072631454.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I4KM9cks-1675570276068)(photo/image-20230205072715293.png)]

4.4 FileOutputStream 应用实例 1 FileOutputStream01.java

要求: 请使用 FileOutputStream 在 a.txt 文件,中写入 “hello,io”. [老师代码演示], 如果文件不存在,会创建

文件(注意:前提是目录已经存在.)

FileOutputStream可以通过三种方式写入数据到文件中,

第一种就是write(),没有任何参数,这种写法就只能写入一个字符

第二种,write(byte[] b),传入一个byte类型数组,这里可以写入多个字符

第三中,write(byte[] b,int off,int len),这样子就可以控制写入文件的字符个数

new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面

代码如下:

package com.yujianedu.outputstream_;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStream_ {
    public static void main(String[] args) {

    }

    /**
     * 演示使用 FileOutputStream 将数据写到文件中, * 如果该文件不存在,则创建该文件
     */
    @Test
    public void writeFile(){
        //创建 FileOutputStream 对象
        String filePath = "D:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            //得到 FileOutputStream 对象 对象
            //老师说明
            //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
            //2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath,true);
            //写入一个字符
            //fileOutputStream.write('G');

            //写入一个字符串
            String str = "hello,io";
            //str.getBytes() 可以把 字符串-> 字节数组
            //fileOutputStream.write(str.getBytes());

            /*
                write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
            */
            fileOutputStream.write(str.getBytes(),0,3);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

4.5 FileOutputStream 应用实例 2 FileCopy.java

要求: 编程完成图片/音乐 的拷贝.

步骤:

  1. 先确定源路径和目的路径
  2. 再将FileInputStream和FileOutputStream创建出来
  3. 然后循环将拷贝的文件进行一点点的读取再写出
  4. 最后将开启的流进行关闭

代码如下:

package com.yujianedu.outputstream_;

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

public class FileCopy {
    public static void main(String[] args) {
        //完成 文件拷贝,将 d:\\iotest\\logo.jpg 拷贝 c:\\logo.jpg
        //思路分析
        //1. 创建文件的输入流 , 将文件读入到程序
        //2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件
        String srcfilePath = "d:\\iotest\\logo.jpg";
        String destfilePath = "c:\\logo.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcfilePath);
            fileOutputStream = new FileOutputStream(destfilePath);
            //定义一个字节数组,提高读取效果
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1){
                //读取到后,就写入到文件 通过 fileOutputStream
                //即,是一边读,一边写
                fileOutputStream.write(buf,0,readLen);//一定要使用这个方法
            }
            File file = new File(destfilePath);
            if (file.exists()){
                System.out.println("拷贝成功");
            }else {
                System.out.println("拷贝失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭输入流和输出流,释放资源
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

4.6 FileReader 和 FileWriter 介绍

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BaTiZsSA-1675570276069)(photo/image-20230205082708100.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UaFh4r6d-1675570276070)(photo/image-20230205082647280.png)]

4.7 FileReader 相关方法:

1)new FileReader(File/String)

2)read:每次读取单个字符,返回该字符,如果到文件末尾返回-1

3)read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1

相关APl:
1)new String(char[]):将char]转换成String

2)new String(char[].off,len):将char]的指定部分转换成String

4.8 FileWriter 常用方法

1)new FileWriter(File/String):覆盖模式,相当于流的指针在首端

2)new FileWriter(File/String,true):追加模式,相当于流的指针在尾端

3)write(int):写入单个字符

4)write(char[]):写入指定数组

5)write(char[],off,len):写入指定数组的指定部分

6)write(string):写入整个字符串

7)write(string,off,len):写入字符串的指定部分相关API:String类:toCharArray:将String转换成char[]

注意:

FileWriter使用后,必须更关闭(close)或刷新(flush),否则写入不到指定的文件

4.9 FileReader 和 FileWriter 应用案例 FileReader_.java

要求:

  1. 使用 FileReader 从 story.txt 读取内容,并显示

使用FileReader进行文件数据读取,可以使用read()与read(char[] c)

第一种:使用read()

/**
* 单个字符读取文件
*/
@Test
public void readFile01(){
    System.out.println("~~~ readFile01 ~~~");
    String filePath = "D:\\iotest\\story.txt";
    FileReader fileReader = null;
    //1. 创建 FileReader 对象
    try {
        int data = 0;
        fileReader = new FileReader(filePath);
        //循环读取 使用 read, 单个字符读取
        while ((data = fileReader.read()) != -1){
            System.out.print((char) data);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fileReader != null){
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

第二种:使用read(char[] c)

/**
* 字符数组读取文件
*/
@Test
public void readFile02(){
    System.out.println("~~~ readFile02 ~~~");
    String filePath = "D:\\iotest\\story.txt";
    FileReader fileReader = null;
    //1. 创建 FileReader 对象
    try {
        int readLen = 0;
        char[] buf = new char[1024];
        fileReader = new FileReader(filePath);
        //循环读取 使用 read(buf), 返回的是实际读取到的字符数
		//如果返回-1, 说明到文件结束
        while ((readLen = fileReader.read(buf)) != -1){
            System.out.print(new String(buf,0,readLen));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (fileReader != null){
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中, 注意细节. FileWriter_.java com.hspedu.writer_

FileWriter有五种方式将数据写入文件

1)write(int):写入单个字符

2)write(char[]):写入指定数组

3)write(char[],off,len):写入指定数组的指定部分

4)write(string):写入整个字符串

5)write(string,off,len):写入字符串的指定部分相关

API:String类:toCharArray:将String转换成char[]

代码如下:

package com.yujianedu.writer_;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "D:\\iotest\\note.txt";
        //创建 FileWriter 对象
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filePath);//默认是覆盖写入
            //1)write(int):写入单个字符
            fileWriter.write('H');
            //2)write(char[]):写入指定数组
            char[] datas1 = {' ','A','B','C','D'};
            fileWriter.write(datas1);
            //3)write(char[],off,len):写入指定数组的指定部分
            char[] data2 = {' ','与','高','给','D'};
            fileWriter.write(data2,0,2);
            //4)write(string):写入整个字符串
            fileWriter.write(" 你好,GoIn");
            fileWriter.write("风雨之后,定见彩虹");
            //5)write(string,off,len):写入字符串的指定部分相关
            fileWriter.write("真的假的,abc",0,4);
            
            //在数据量大的情况下,可以使用循环操作.

            System.out.println("添加成功~~~");
        } catch (IOException e) {
            e.printStackTrace();
        }finally { //对应 FileWriter , 一定要关闭流,或者 flush 才能真正的把数据写入到文件
            try {
                //fileWriter.flush();
				//关闭文件流,等价 flush() + 关闭
                if (fileWriter != null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5. 节点流和处理流

5.1 基本介绍

  1. 节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter[源码]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XgINF4w0-1675570276070)(photo/image-20230205115821442.png)]

  1. 处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter[源码]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eNqw2qoR-1675570276071)(photo/image-20230205120249016.png)]

5.2 节点流和处理流一览图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xm1YI3uq-1675570276071)(photo/image-20230205112818468.png)]

5.3 节点流和处理流的区别和联系

  • 节点流原理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ym5cJY9k-1675570276072)(photo/image-20230205113159612.png)]

  • 处理流原理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gMLsBoPb-1675570276073)(photo/image-20230205120509240.png)]

1.节点流是底层流/低级流,直接跟数据源相接。
2.处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。[源码理解]
3.处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连 [模拟修饰器设计模式=》小伙伴就会非常清楚.]

5.4 处理流的功能主要体现在以下两个方面:

1.性能的提高:主要以增加缓冲的方式来提高输入输出的效率。
2.操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便

5.5 处理流-BufferedReader 和 BufferedWriter

  • BufferedReader和BufferedWriter 属于字符流,是按照字符来读取数据的
  • 关闭时处理流,只需要关闭外层流即可[后面看源码]
  • 应用案例
  1. 使用BufferedReader 读取文本文件,并显示在控制台BufferedReader.java

代码如下:

package com.yujianedu.reader_;

import java.io.BufferedReader;
import java.io.FileReader;

public class BufferedReader_ {
    public static void main(String[] args) throws Exception {
        String filePath = "D:\\iotest\\story.txt";
        //创建bufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        String line ; //按行读取,效率高
        //说明
        //1.bufferedReader.readLine()是按行读取文件
        //2.当返回null时,表示文件读取完毕
        while ((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }

        // 关闭流,这里注意,只需要关闭BufferedReader,因为底层会自动的去关闭节点流
        // FileReader。
        bufferedReader.close();
    }
}
  1. 使用BufferedWriter将”hello,韩顺平教育”,写入到文件中 BufferedWriter_.java
package com.yujianedu.writer_;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\iotest\\ok.txt";
        //创建BufferedWriter
        // 说明:
        //1.new FileWriter(filePath,true)表示以追加的方式写入
        //2.new FileWriter(filePath),表示以覆盖的方式写入
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));

        bufferedWriter.write("hello,咱们一起学习");
        bufferedWriter.newLine(); // 插入一个和系统相关的换行
        bufferedWriter.write("hello,咱们一起学习");
        bufferedWriter.newLine();
        bufferedWriter.write("hello,咱们一起学习");
        bufferedWriter.newLine();

        // 说明:关闭外层流即可,传入的new FileWriter(filePath),会在底层关闭
        bufferedWriter.close();
    }
}
  1. 综合使用BufferedReader 和BufferedWriter 完成文本文件拷贝,注意文件编码 BufferedCopy.java
package com.yujianedu.writer_;

import java.io.*;

public class BufferedCopy_ {
    public static void main(String[] args) throws IOException {

        //老韩说明
        //1. BufferedReader 和 BufferedWriter 是安装字符操作
        //2. 不要去操作 二进制文件[声音,视频,doc, pdf ], 可能造成文件损坏

        String srcFilePath = "D:\\iotest\\story.txt";
        String descFilePath = "D:\\iotest\\story1.txt";

        BufferedReader bufferedReader = new BufferedReader(new FileReader(srcFilePath));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(descFilePath));

        String line;

        while ((line = bufferedReader.readLine()) != null){
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }

        System.out.println("copy成功~~~");

        //关闭流(先启动的后关闭)
        bufferedWriter.close();
        bufferedReader.close();

    }
}

5.6 处理流-BufferedInputStream 和 BufferedOutputStream

  • 介绍BufferedInputStream

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R7bgxURW-1675598840638)(photo/image-20230205165509439.png)]

BufferedInputStream是字节流,在创建 BufferedInputStream时,会创建一个内部缓冲区数组.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XNj8hmFC-1675598840640)(photo/image-20230205154818537.png)]

5.7 介绍 BufferedOutputStream

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nHPK0hlP-1675598840641)(photo/image-20230205165605609.png)]

BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4703rIOj-1675598840641)(photo/image-20230205154727453.png)]

应用案例
要求:编程完成图片/音乐的拷贝(要求使用Buffered..流).[老师代码演示]BufferedCopy02.java

package com.yujianedu.writer_;

import java.io.*;

public class BufferedCopy02 {
    public static void main(String[] args) {
        String srcfilePath = "D:\\iotest\\logo.jpg";
        String descfilePath = "D:\\iotest\\logo1.jpg";
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //因为 FileInputStream 是 InputStream 子类
            bis = new BufferedInputStream(new FileInputStream(srcfilePath));
            bos = new BufferedOutputStream(new FileOutputStream(descfilePath));

            //循环的读取文件,并写入到 destFilePath
            byte[] buf = new byte[1024];
            int readLen = 0;
            //当返回 -1 时,就表示文件读取完毕
            while ((readLen = bis.read(buf)) != -1){
                bos.write(buf,0,readLen);
            }
            System.out.println("copy成功~~~");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流 , 关闭外层的处理流即可,底层会去关闭节点流
            try {
                bos.close();
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5.8 对象流-ObjectInputStream 和 ObjectOutputStream

看一个需求
1.将int num=100这个int 数据保存到文件中,注意不是100数字,而是int100,并且,能够从文件中直接恢复int 100

2.将Dog dog=new Dog(“小黄”,3)这个dog对象保存到文件中,并且能够从文件恢复。

3.上面的要求,就是能够将基本数据类型或者对象进行序列化和反序列化操作

序列化和反序列化
1.序列化就是在保存数据时,保存数据的值数据类型

2.反序列化就是在恢复数据时,恢复数据的值数据类型

3.需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:

Serializable//这是一个标记接口,没有方法(推荐使用)

Externalizable//该接口有方法需要实现,因此我们一般实现上面的 Serializable接口

5.9 对象流介绍

功能:提供了对基本类型或对象类型的序列化和反序列化的方法

ObjectOutputStream 提供 序列化功能

ObjectInputStream 提供 反序列化功能

应用案例

  1. 使用ObjectOutputStream 序列化基本数据类型和一个Dog对象(name,age),并保存到 data.dat 文件中ObjectOutStream,java
package com.yujianedu.outputstream_;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 演示 ObjectOutputStream 的使用, 完成数据的序列化
 */
public class ObjectOutputStream_ {
    public static void main(String[] args) throws Exception{
        //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "d:\\iotest\\data.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
        //序列化数据到 d:\iotest\data.dat
        oos.writeInt(100); // int -> Integer (实现了 Serializable)
        oos.writeBoolean(true); // boolean -> Boolean (实现了 Serializable)
        oos.writeChar('a');// char -> Character (实现了 Serializable)
        oos.writeDouble(9.7); // double -> Double (实现了 Serializable)
        oos.writeUTF("你好,IO学习"); //String
        //保存一个 dog 对象
        oos.writeObject(new Dog("小黄",10));

        System.out.println("数据保存完毕(序列化)");

        oos.close();

    }
}

//如果需要序列化某个类的对象,需要实现 Serializable
class Dog implements Serializable {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
  1. 使用ObjectlnputStream 读取 data.dat 并反序列化恢复数据
package com.yujianedu.inputstream_;

import com.yujianedu.outputstream_.Dog;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filePath = "D:\\iotest\\data.dat";

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        // 2.读取, 注意顺序
        /*
            1.读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
            2.否则会出现异常
         */
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        //dog的编译类型是Object,dog的运行类型是Dog
        Object dog = ois.readObject();
        System.out.println("运行类型="+ dog.getClass());
        System.out.println("dong信息"+dog); //底层 Object -> Dog

        //这里特别重要的细节:
        //1. 如果我们希望调用Dog中的方法,需要向下转型
        //2. 需要我们将Dog类的定义,放到可以引用的地方
        Dog dog2 = (Dog) dog;
        System.out.println(dog2.getName());
        System.out.println(dog2.getAge());
        // 3.关闭
        ois.close();
        System.out.println("以反序列化的方式读取(恢复)ok~");
    }
}
  • 注意事项和细节说明

    1. 读写顺序要一致

    2. 要求序列化或反序列化对象,需要实现 Serializable

    3. 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性

      // SerialVersionUID 序列化版本号,可以提高兼容性
      private static final long SerialVersionUID = 1L;
      

      意思就是:当你有了这个 SerialVersionUID 字段之后,当你以后再往类中添加了属性,它会认为你只是类的版本进行了修改,不会认为是一个新的类

    4. 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员

    5. 序列化对象时,要求里面属性的类型也需要实现序列化接口

    6. 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化

5.10 标准输入输出流

  • 先创建一个类 com.yujianedu.standard InputAndOutput.java

  • 介绍

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iBEcx2fp-1675655671196)(photo/image-20230206102401434.png)]

应用案例1传统方法System.out.println("");是使用 out 对象将数据输出到显示器
应用案例2传统的方法,Scanner 是从标准输入键盘接收数据

package com.yujianedu.standard;

public class InputAndOutput {
    public static void main(String[] args) {
        //System类的 pubLic final static Inputstream in=null;
        //System.in 编译类型 InputStream
        //System.in 运行类型 BufferedInputStream
        //表示的是标准输入键盘
        System.out.println(System.in.getClass());

        //老韩解读
        //1.System.out public final static Printstream out=null;
        //2.编译类型Printstream//3.运行类型Printstream
        //4.表示标准输出显示器
        System.out.println(System.out.getClass());

        System.out.println("hello,你好,一起学习IO");
    }
}

5.11 转换流-InputStreamReader 和 OutputStreamWriter

创建一个新的java文件com.yujianedu.tranformation.CodeQuestion.java

先看一个文件乱码问题,引出学习转换流必要性.

package com.yujianedu.tranformation;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 看一个中文乱码问题
 */
public class CodeQuestion {
    public static void main(String[] args) throws IOException {
        //读取 d:\\iotest\\a.txt
        //思路:
        //1.创建一个字符输入流 BufferedReader [处理流]
        //2. 使用 BufferedReader 来读取文件
        //3. 默认情况下,读取文件是按照 utf-8 编码
        String filePath = "d:\\iotest\\a.txt";
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }
        br.close();
    }
}

执行结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CJoqEmt6-1675655671197)(photo/image-20230206104228143.png)]

  • 介绍
    1. InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成(转换)Reader(字符流)
    2. OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
    3. 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
    4. 可以在使用时指定编码格式(比如 utf-8,gbk,gb2312,ISO8859-1等)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-91lSX8jL-1675655671198)(photo/image-20230206104456360.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xiKUmFkF-1675655671199)(photo/image-20230206104715955.png)]

  • 应用案例

    1. 编程将字节流FilelnputStream 包装成(转换成)字符流InputStreamReader,对文件进行读取(按照 utf-8/gbk 格式),进而在包装成BufferedReader

    创建一个类 InputStreamReader_.java 来进行操作

package com.yujianedu.tranformation;

import java.io.*;

/**
 * 演示使用 InputStreamReader 转换流解决中文乱码问题
 * 将字节流 FileInputStream 转成字符流 InputStreamReader, 指定编码 gbk/utf-8
 */
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\iotest\\a.txt";

        //解读
        //1. 把 FileInputStream 转成 InputStreamReader
        //2. 指定编码 gbk
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath),"gbk");
        //3. 把 InputStreamReader 传入 BufferedReader
        BufferedReader br = new BufferedReader(isr);

        //将2和3合并
        br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));
        //4. 读取
        System.out.println(br.readLine());
        //5. 关闭外层流
        br.close();
    }
}
  • 应用案例

    编程将字节流 FileOutputStream包装成(转换成)字符流OutputStreamWriter,对文件进行写入(按照gbk格式,可以指定其他,比如utf-8)

package com.yujianedu.tranformation;

import java.io.*;

public class OutputStramWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\iotest\\osw.txt";
        String charSet = "gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
        osw.write("hi,一直都在学习!!!");
        osw.close();
        System.out.println("按照" + charSet + "保存文件成功~~");
    }
}

6. 打印流-PrintStream 和 PrintWriter

com.yujianedu.printstream PrintStream.java PrintWriter.java

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FTnyoGbR-1675655671199)(photo/image-20230206112223392.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tJbAymHB-1675655671200)(photo/image-20230206112308670.png)]

  • 应用实例,打印流只有输出流,没有输入流

    1. PrintStream_.java
    package com.yujianedu.printstream;
    
    import java.io.IOException;
    import java.io.PrintStream;
    
    public class PrintStream_ {
        public static void main(String[] args) throws IOException {
            PrintStream out = System.out;
            //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
            out.print("yujian,hello");
    
            //因为print底层使用的是write,所以我们可以直接调用write进行打印
            out.write("大家好,那么好".getBytes());
    
            //我们可以去修改打印流输出的位置
            System.setOut(new PrintStream("d:\\iotest\\ps.txt"));
            System.out.println("发挥大开发的哈弗");
    
            out.close();
    
    
        }
    }
    
    1. PrintWriter_
    package com.yujianedu.printstream;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class PrintWriter_ {
        public static void main(String[] args) throws IOException {
            //PrintWriter pw = new PrintWriter(System.out);
            PrintWriter pw = new PrintWriter(new FileWriter("d:\\iotest\\pw.txt"));
            pw.println("hi,dajia1askfdhl");
            pw.close();
        }
    }
    

7. Properties 类

7.1 看一个需求

如下有一个配置文件 mysql.properties

ip=192.168.0.13

user=root

pwd=12345

请问编程读取ip、user和pwd的值是多少

  • 分析
    1. 传统的方法
    2. 使用Properties类可以方便实现

7.2 基本介绍

  1. 专门用于读写配置文件的集合类
    配置文件的格式:
    键=值键=值

  2. 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String

  3. Properties的常见方法

    load:加载配置文件的键值对到Properties对象

    list:将数据显示到指定设备

    getProperty(key):根据键获取值

    setProperty(key,value):设置键值对到Properties对象

    store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码

7.3 应用案例

  1. 首先我们先来看看如何读取一个properties文件
package com.yujianedu.properties;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class Properties02 {
    public static void main(String[] args) throws IOException {
        // 使用Properties类来读取mysqL.properties文件

        //1. 创建 Properties 对象
        Properties properties = new Properties();

        //2.加载指定配置文件
        properties.load(new FileReader("src\\mysql.properties"));
        //3.将k-v显示到控制台
        properties.list(System.out);
        //4. 根据key获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println(user);
        System.out.println(pwd);
    }
}

执行结果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BX7MlxmP-1675668319693)(photo/image-20230206140428166.png)]

  1. 我们下面来展示下如何通过Properties类来创建properties文件
package com.yujianedu.properties;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Properties03 {
    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();

        //创建
        //1. 如果该文件没有key,就是创建
        //2. 如果该文件有key,就是修改
        properties.setProperty("charset","utf8");
        properties.setProperty("name","硬币"); //注意保存时,是中文的 unicode 码值
        properties.setProperty("pwd","121212");

        //将 k-v 存储到文件中
        //store有2个参数,第一个参数:存储文件的路径,第二个参数:文件的注释(一般情况下为null)
        properties.store(new FileOutputStream("src\\mysql2.properties"),null);
        System.out.println("保存配置文件成功~~~");
    }
}

8.本章作业

1.编程题 Homework01.java 5min一定要自己做.

(1)在判断e盘下是否有文件夹mytemp,如果没有就创建mytemp

(2)在e:\mytemp 目录下,创建文件hello.txt

(3)如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了

(4)并且在hello.txt 文件中,写入hello,world~

package com.yujianedu.homework;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class HomeWork1 {
    public static void main(String[] args) throws IOException {
        String parentDest = test01();
        String filename = "hello.txt";
        File file = new File(parentDest, filename);
        try {
            file.createNewFile();
            if (file.exists()){
                System.out.println(filename + "文件创建成功~~");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String filePath = file.getAbsolutePath();
        FileWriter fileWriter = new FileWriter(filePath);
        fileWriter.write("hello,world~");
        fileWriter.close();

    }

    public static String test01(){
        String filePath = "D:\\mytemp";
        File file = new File(filePath);
        if (! file.exists()){
            file.mkdir();
        }
        return filePath;
    }
}

2.编程题 Homework02.java要求:使用BufferedReader读取一个文本文件,为每行加上行号,再连同内容一并输出到屏幕上。

//如果老韩把文件的编码改成了gbk,出现中文乱码,大家思考如何解决

//1.默认是按照 utf-8处理,开始没有乱码
//2.提示:使用我们的转换流,将FilelnputStream->InputStreamReader[可以指定编码]->BufferedReader..…

package com.yujianedu.homework;

import java.io.*;

public class Homework2 {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\\iotest\\story.txt";
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"utf-8"));

        String line;
        int cow = 0;
        while ((line = br.readLine()) != null){
            System.out.print((++cow)+" ");
            System.out.println(line);
        }

        br.close();
    }
}

3.编程题 Homework03.java
(1)要编写一个dog.properties name=tom age=5 color=red
(2)编写Dog 类(name,age,color)创建一个dog对象,读取dog.properties 用相应的内容完成属性初始化,并输出
(3)将创建的Dog对象,序列化到文件 dog.dat文件

package com.yujianedu.homework;

import org.junit.Test;

import java.io.*;
import java.util.Properties;

public class Homewok3 {
    public static void main(String[] args) throws IOException {
        String filePath = "src\\dog.properties";
        Properties properties = new Properties();
        properties.load(new FileReader(filePath));
        String name = properties.getProperty("name");
        int age = Integer.parseInt(properties.getProperty("age"));
        String color = properties.getProperty("color");

        Dog dog = new Dog(name, age, color);
        System.out.println("===== dog的信息 =====");
        System.out.println(dog);

        //将创建的Dog对象,序列化到文件 dog.dat 中
        String serFilePath = "d:\\iotest\\dog.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
        oos.writeObject(dog);

        oos.close();
        System.out.println("dog序列化成功~~~");
    }

    @Test
    public void m1() throws IOException, ClassNotFoundException {
        String serFilePath = "d:\\iotest\\dog.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));

        Dog dog = (Dog) ois.readObject();
        System.out.println("===== 反序列化成功 =====");
        System.out.println(dog);
    }
}

class Dog implements Serializable {
    private String name;
    private int age;
    private String color;

    public Dog(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}
posted @ 2023-02-16 16:09  GD1_1DG  阅读(32)  评论(0编辑  收藏  举报
Language: HTML