找回密码
 立即注册
首页 业界区 安全 第 15 章IO流

第 15 章IO流

凉砧掌 昨天 13:55
第 15 章IO流

15.1 文件

15.1.1 什么是文件

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

1.png

15.2 常用的文件操作

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

<img alt="image-20250831195933714" >
  1. package com.ming.file;
  2. import org.junit.jupiter.api.Test;
  3. import java.io.File;
  4. import java.io.IOException;
  5. /**
  6. * @author 明
  7. * @version 1.0
  8. */
  9. public class FileCreate {
  10.     public static void main(String[] args) {
  11.     }
  12.     //方式1 new File(String pathname)
  13.     @Test
  14.     public void create01(){
  15.         String filePath = "D:/JAVA/韩顺平/代码/chapter19/1.txt";
  16.         File file = new File(filePath);
  17.         try {
  18.             file.createNewFile();
  19.             System.out.println("文件创建成功");
  20.         } catch (IOException e) {
  21.             e.printStackTrace();
  22.         }
  23.     }
  24.     //方式2 new File(File parent,String child) //根据父目录文件+子路径构建
  25.     //D:/JAVA/韩顺平/代码/chapter19/2.txt
  26.     @Test
  27.     public void create02(){
  28.         File parent =  new File("D:/JAVA/韩顺平/代码/chapter19/");
  29.         String fileName = "2.txt";
  30.         //这里的file对象,在java程序中,只是一个对象
  31.         //只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
  32.         File file = new File(parent, fileName);
  33.         try {
  34.             file.createNewFile();
  35.             System.out.println("文件创建成功");
  36.         } catch (IOException e) {
  37.             e.printStackTrace();
  38.         }
  39.     }
  40.     @Test
  41.     //方式3 new File(String parent,String child) //根据父目录+子路径构建
  42.     public void create03(){
  43.         String parent = "D:/JAVA/韩顺平/代码/chapter19/";
  44.         String fileName = "3.txt";
  45.         File file = new File(parent,fileName);
  46.         try {
  47.             file.createNewFile();
  48.             System.out.println("文件创建成功");
  49.         } catch (IOException e) {
  50.             e.printStackTrace();
  51.         }
  52.     }
  53. }
复制代码
15.2.2 获取文件的相关信息

getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
2.png

15.2.3 应用案例演示 FileInformation.java

如何获取到文件的大小,文件名,路径,父File,是文件还是目录(目录本质也是文件,一种特殊的文件),是否存在。
  1. package com.ming.file;
  2. import org.junit.jupiter.api.Test;
  3. import java.io.File;
  4. /**
  5. * @author 明
  6. * @version 1.0
  7. */
  8. public class FileInformation {
  9.     public static void main(String[] args) {
  10.     }
  11.     //获取文件的信息
  12.     @Test
  13.     public void info() {
  14.         //先创建文件对象
  15.         File file = new File("D:/JAVA/韩顺平/代码/chapter19/1.txt");
  16.         //调用相应的方法,得到对应信息
  17.         System.out.println("文件名字=" + file.getName());
  18.         //getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
  19.         System.out.println("文件绝对路径=" + file.getAbsolutePath());
  20.         System.out.println("文件父级目录=" + file.getParent());
  21.         System.out.println("文件大小(字节)=" + file.length());
  22.         System.out.println("文件是否存在=" + file.exists());//T
  23.         System.out.println("是不是一个文件=" + file.isFile());//T
  24.         System.out.println("是不是一个目录=" + file.isDirectory());//F
  25.     }
  26. }
复制代码
15.2.4 目录的操作和文件删除

<img alt="image-20250831214156637" >
  1. public class Directory_ {
  2.     public static void main(String[] args) {
  3.     }
  4.     @Test
  5.     public void test01() {
  6.         String filePath = "D:/JAVA/韩顺平/代码/chapter19/3.txt";
  7.         File file = new File(filePath);
  8.         if(file.exists()){
  9.             if(file.delete()){
  10.             System.out.println(filePath + "删除成功");
  11.             } else {
  12.                 System.out.println(filePath + "删除失败");
  13.             }
  14.         } else {
  15.             System.out.println("该文件不存在...");
  16.         }
  17.     }
  18.     //判断 D:\\demo02 是否存在,存在就删除,否则提示不存在
  19.     //这里我们需要体会到,在java编程中,目录也被当做文件
  20.     @Test
  21.     public void m2() {
  22.         String filePath = "D:\\demo02";
  23.         File file = new File(filePath);
  24.         if (file.exists()) {
  25.             if (file.delete()) {
  26.                 System.out.println(filePath + "删除成功");
  27.             } else {
  28.                 System.out.println(filePath + "删除失败");
  29.             }
  30.         } else {
  31.             System.out.println("该目录不存在...");
  32.         }
  33.     }
  34.     //判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
  35.     @Test
  36.     public void m3() {
  37.         String directoryPath = "D:\\demo\\a\\b\\c";
  38.         File file = new File(directoryPath);
  39.         if (file.exists()) {
  40.             System.out.println(directoryPath + "存在..");
  41.         } else {
  42.             if (file.mkdirs()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()
  43.                 System.out.println(directoryPath + "创建成功..");
  44.             } else {
  45.                 System.out.println(directoryPath + "创建失败...");
  46.             }
  47.         }
  48.     }
  49. }
复制代码
15.3 IO 流原理及流的分类

15.3.1 Java IO 流原理


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


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

  • Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。
  • 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
15.4 IO 流体系图-常用的类

1. IO 流体系图

3.png

2. 文件 VS 流


4.png

15.4.1 FileInputStream 介绍

15.4.2 FileInputStream 应用实例 FileInputStream_.java
  1. package com.ming.inputstream_;
  2. import org.junit.jupiter.api.Test;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. /**
  7. * @author 明
  8. * @version 1.0
  9. */
  10. public class FileInputStream_ {
  11.     public static void main(String[] args) {
  12.     }
  13.     /**
  14.      * 演示读取文件...
  15.      * 单个字节的读取,效率比较低
  16.      * -> 使用 read(byte[] b)
  17.      */
  18.     @Test
  19.     public void readFile01() {
  20.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\1.txt";
  21.         int readData = 0;
  22.         FileInputStream fileInputStream = null;
  23.         try {
  24.             //创建 FileInputStream 对象,用于读取 文件
  25.             fileInputStream = new FileInputStream(filePath);
  26.             //从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
  27.             //如果返回-1 , 表示读取完毕
  28.             while ((readData = fileInputStream.read()) != -1) {
  29.                 System.out.print((char)readData);//转成char显示
  30.             }
  31.         } catch (IOException e) {
  32.             e.printStackTrace();
  33.         } finally {
  34.             //关闭文件流,释放资源.
  35.             try {
  36.                 fileInputStream.close();
  37.             } catch (IOException e) {
  38.                 e.printStackTrace();
  39.             }
  40.         }
  41.     }
  42.     /**
  43.      * 使用 read(byte[] b) 读取文件,提高效率
  44.      */
  45.     @Test
  46.     public void readFile02() {
  47.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\1.txt";
  48.         //字节数组
  49.         byte[] buf = new byte[8]; //一次读取8个字节.
  50.         int readLen = 0;
  51.         FileInputStream fileInputStream = null;
  52.         try {
  53.             //创建 FileInputStream 对象,用于读取 文件
  54.             fileInputStream = new FileInputStream(filePath);
  55.             //从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
  56.             //如果返回-1 , 表示读取完毕
  57.             //如果读取正常, 返回实际读取的字节数
  58.             while ((readLen = fileInputStream.read(buf)) != -1) {
  59.                 System.out.print(new String(buf, 0, readLen));//显示
  60.             }
  61.         } catch (IOException e) {
  62.             e.printStackTrace();
  63.         } finally {
  64.             //关闭文件流,释放资源.
  65.             try {
  66.                 fileInputStream.close();
  67.             } catch (IOException e) {
  68.                 e.printStackTrace();
  69.             }
  70.         }
  71.     }
  72. }
复制代码
15.4.3 FileOutputStream 介绍

5.png

15.4.4 FileOutputStream 应用实例 1 FileOutputStream01.java
  1. package com.ming.outputstream_;
  2. import org.junit.jupiter.api.Test;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. /**
  7. * @author 明
  8. * @version 1.0
  9. */
  10. public class FileOutputStream_ {
  11.     public static void main(String[] args) {
  12.     }
  13.     @Test
  14.     public void f(){
  15.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\3.txt";
  16.         FileOutputStream fileOutputStream = null;
  17.         try {
  18.             //得到 FileOutputStream对象 对象
  19.             //老师说明
  20.             //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
  21.             //2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
  22.             fileOutputStream = new FileOutputStream(filePath);
  23.             //写入一个字节
  24.             //fileOutputStream.write('H');//
  25.             //写入字符串
  26.             String str = "ming,world!";
  27.             //str.getBytes() 可以把 字符串-> 字节数组
  28.             //fileOutputStream.write(str.getBytes());
  29.             /*
  30.             write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
  31.              */
  32.             fileOutputStream.write(str.getBytes(), 0, 3);
  33.         } catch (IOException e) {
  34.             e.printStackTrace();
  35.         } finally {
  36.             try {
  37.                 fileOutputStream.close();
  38.             } catch (IOException e) {
  39.                 e.printStackTrace();
  40.             }
  41.         }
  42.     }
  43. }
复制代码
15.4.5 FileOutputStream应用实例2 FileCopy.java
  1. package com.ming.outputstream_;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. /**
  7. * @author 明
  8. * @version 1.0
  9. */
  10. public class FileCopy {
  11.     //思路分析
  12.     //1. 创建文件的输入流 , 将文件读入到程序
  13.     //2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件.
  14.     public static void main(String[] args) {
  15.         String infilePath = "C:/Users/yemin/Pictures/5.png";
  16.         String outfilePath = "C:/Users/yemin/Pictures/555.png";
  17.         FileInputStream fis = null;
  18.         FileOutputStream fos = null;
  19.         try {
  20.             fis = new FileInputStream(infilePath);
  21.             fos = new FileOutputStream(outfilePath);
  22. //            int len = 0;
  23. //            while((len = fis.read()) != -1){
  24. //                fos.write(len);
  25. //            }
  26.             //读取到后,就写入到文件 通过 fileOutputStream
  27.             //即,是一边读,一边写
  28.             byte[] buffer = new byte[1024];
  29.             int readlen = 0;
  30.             while((readlen = fis.read(buffer)) != -1){
  31.                 fos.write(buffer,0,readlen);
  32.             }
  33.         } catch (IOException e) {
  34.             e.printStackTrace();
  35.         } finally {
  36.             try {
  37.                 fis.close();
  38.                 fos.close();
  39.             } catch (IOException e) {
  40.                 e.printStackTrace();
  41.             }
  42.         }
  43.     }
  44. }
复制代码
15.4.6 FileReader 和 FileWriter 介绍

6.png

15.4.7 FileReader 相关方法:


  • new FileReader(File/String)
  • read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
  • read(char[]): 批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1
相关API:

  • new String(char[]):将char[]转换成String
  • new String(char[],off,len):将char[]的指定部分转换成String
15.4.8 FileWriter 常用方法


  • new FileWriter(File/String): 覆盖模式,相当于流的指针在首端
  • new FileWriter(File/String,true): 追加模式,相当于流的指针在尾端
  • write(int):写入单个字符
  • write(char[]):写入指定数组
  • write(char[],off,len):写入指定数组的指定部分
  • write (string): 写入整个字符串
  • write(string,off,len):写入字符串的指定部分
相关API:String类:toCharArray:将String转换成char[]
注意:
FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!
15.4.9 FileReader 和 FileWriter 应用案例 FileReader_.java

要求:

  • 使用FileReader 从 story.txt 读取内容,并显示
  1. package com.ming.reader_;
  2. import org.junit.jupiter.api.Test;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6. /**
  7. * @author 明
  8. * @version 1.0
  9. */
  10. public class FileReader_ {
  11.     public static void main(String[] args) {
  12.     }
  13.     /**
  14.      * 单个字符读取文件
  15.      */
  16.     @Test
  17.     public void readFile01() throws IOException {
  18.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\1.txt";
  19.         FileReader fileReader = null;
  20.         int data = 0;
  21.         //1. 创建FileReader对象
  22.         try {
  23.             fileReader = new FileReader(filePath);
  24.             while((data = fileReader.read()) != -1){
  25.                 System.out.print((char)data);
  26.             }
  27.         } catch (IOException e) {
  28.             e.printStackTrace();
  29.         }finally {
  30.             fileReader.close();
  31.         }
  32.     }
  33.     /**
  34.      * 字符数组读取文件
  35.      */
  36.     @Test
  37.     public void readFile02() throws IOException {
  38.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\1.txt";
  39.         FileReader fileReader = null;
  40.         int readlen = 0;
  41.         char[] chars = new char[1024];
  42.         //1. 创建FileReader对象
  43.         try {
  44.             fileReader = new FileReader(filePath);
  45.             while((readlen = fileReader.read(chars)) != -1){
  46.                 System.out.print(new String(chars,0,readlen));
  47.             }
  48.         } catch (IOException e) {
  49.             e.printStackTrace();
  50.         }finally {
  51.             fileReader.close();
  52.         }
  53.     }
  54. }
复制代码
15.5 节点流和处理流

15.5.1 基本介绍

7.png

15.5.2 节点流和处理流一览图

分 类字节输入流字节输出流字符输入流字符输出流抽象基类InputStreamOutputStreamReaderWriter访问文件FileInputStreamFileOutputStreamFileReaderFileWriter访问数组ByteArrayInputStreamByteArrayOutputStreamCharArrayReaderCharArrayWriter访问管道PipedInputStreamPipedOutputStreamPipedReaderPipedWriter访问字符串StringReaderStringWriter缓冲流BufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriter转换流InputStreamReaderOutputStreamWriter对象流ObjectInputStreamObjectOutputStream抽象基类FilterInputStreamFilterOutputStreamFilterReaderFilterWriter打印流PrintStreamPrintWriter推回输入流PushbackInputStreamPushbackReader特殊流DataInputStreamDataOutputStream15.5.3 节点流和处理流的区别和联系


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


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


  • BufferedReader 和 BufferedWriter 属于字符流,是按照字符来读取数据的
  • 关闭时处理流,只需要关闭外层流即可[后面看源码]
应用案例


  • 使用BufferedReader 读取文本文件,并显示在控制台 BufferedReader_.java
  1. package com.ming.reader_;
  2. import java.io.BufferedReader;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileReader;
  5. /**
  6. * @author 明
  7. * @version 1.0
  8. */
  9. public class BuffererReader_ {
  10.     public static void main(String[] args) throws Exception {
  11.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\2.txt";
  12.         //创建bufferedReader
  13.         BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
  14.         //读取
  15.         String line;//按行读取效率高
  16.         //说明
  17.         //1. bufferedReader.readLine() 是按行读取文件
  18.         //2. 当返回null 时,表示文件读取完毕
  19.         while((line = bufferedReader.readLine()) != null){
  20.             System.out.println(line);
  21.         }
  22.         //关闭流, 这里注意,只需要关闭 BufferedReader ,因为底层会自动的去关闭 节点流
  23.         //FileReader。
  24.         /*
  25.             public void close() throws IOException {
  26.                 synchronized (lock) {
  27.                     if (in == null)
  28.                         return;
  29.                     try {
  30.                         in.close();//in 就是我们传入的 new FileReader(filePath), 关闭了.
  31.                     } finally {
  32.                         in = null;
  33.                         cb = null;
  34.                     }
  35.                 }
  36.             }
  37.          */
  38.         bufferedReader.close();
  39.     }
  40. }
复制代码
15.5.6 处理流-BufferedInputStream 和 BufferedOutputStream

8.png

15.5.7 介绍BufferedOutputStream

9.png
  1. package com.ming.outputstream_;
  2. import java.io.*;
  3. /**
  4. * @author 明
  5. * @version 1.0
  6. */
  7. public class BufferedCopy02 {
  8.     public static void main(String[] args) throws IOException {
  9.         String srcFilePath = "C:/Users/yemin/Pictures/1.jpg";
  10.         String destFilePath = "C:/Users/yemin/Pictures/111.jpg";
  11.         BufferedInputStream bis = null;
  12.         BufferedOutputStream bos = null;
  13.         bis = new BufferedInputStream(new FileInputStream(srcFilePath));
  14.         bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
  15.         byte[] buffer = new byte[1024];
  16.         int len = 0;
  17.         while((len = bis.read(buffer)) != -1){
  18.             bos.write(buffer,0,len);
  19.         }
  20.         bis.close();
  21.         bos.close();
  22.         System.out.println("拷贝完毕");
  23.     }
  24. }
复制代码
15.5.8 对象流-ObjectInputStream 和 ObjectOutputStream

看一个需求

  • 将int num = 100这个int数据保存到文件中,注意不是 100 数字,而是 int 100,并且,能够从文件中直接恢复 int 100
  • 将 Dog dog = new Dog(“小黄”, 3) 这个 dog 对象保存到文件中,并且能够从文件恢复。
  • 上面的要求,就是能够将 基本数据类型 或者 对象 进行 序列化和反序列化操作
序列化和反序列化

  • 序列化就是在保存数据时,保存数据的值和数据类型
  • 反序列化就是在恢复数据时,恢复数据的值和数据类型
  • 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:

    • Serializable:这是一个标记接口,没有方法
    • Externalizable:该接口有方法需要实现,因此我们一般实现上面的 Serializable 接口
      10.png


15.5.9 对象流介绍

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

应用案例


  • 使用ObjectOutputStream 序列化 基本数据类型和一个 Dog对象(name, age), 并保存到 data.dat 文件中 ObjectOutStream_.java
    1. package com.ming.outputstream_;
    2. import java.io.FileOutputStream;
    3. import java.io.ObjectOutputStream;
    4. /**
    5. * @author 明
    6. * @version 1.0
    7. */
    8. public class ObjectOutStream_ {
    9.     public static void main(String[] args) throws Exception{
    10.         //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
    11.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\5.dat";
    12.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
    13.         oos.writeInt(100);
    14.         oos.writeBoolean(true);
    15.         oos.writeChar('a');
    16.         oos.writeDouble(9.5);
    17.         oos.writeUTF("解放的快");
    18.         //保存一个dog对象
    19.         oos.writeObject(new Dog("旺财", 10, "日本", "白色"));
    20.         oos.close();
    21.         System.out.println("数据保存完毕(序列化形式)");
    22.     }
    23. }
    24. class  Dog implements Serializable {
    25.     private String name;
    26.     private int age;
    27.     //序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
    28.     private static String nation;
    29.     private transient String color;
    30.     //序列化对象时,要求里面属性的类型也需要实现序列化接口
    31.     private Master master = new Master();
    32.     //serialVersionUID 序列化的版本号,可以提高兼容性
    33.     private static final long serialVersionUID = 1L;
    34.     public Dog(String name, int age, String nation, String color) {
    35.         this.name = name;
    36.         this.age = age;
    37.         this.color = color;
    38.         this.nation = nation;
    39.     }
    40.     @Override
    41.     public String toString() {
    42.         return "Dog{" +
    43.                 "name='" + name + '\'' +
    44.                 ", age=" + age +
    45.                 ", color='" + color + '\'' +
    46.                 '}' + nation + " " +master;
    47.     }
    48.     public String getName() {
    49.         return name;
    50.     }
    51.     public void setName(String name) {
    52.         this.name = name;
    53.     }
    54.     public int getAge() {
    55.         return age;
    56.     }
    57.     public void setAge(int age) {
    58.         this.age = age;
    59.     }
    60. }
    61. class Master implements Serializable {
    62. }
    复制代码
  • 使用ObjectInputStream 读取 data.dat 并反序列化恢复数据
  1. package com.ming.inputstream_;
  2. import com.ming.outputstream_.Dog;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.ObjectInputStream;
  6. /**
  7. * @author 明
  8. * @version 1.0
  9. */
  10. public class ObjectInputStream_ {
  11.     public static void main(String[] args) throws Exception {
  12.         //指定反序列化的文件
  13.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\5.dat";
  14.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
  15.         //读取
  16.         //1. 读取(反序列化)的顺序顺序和你保存数据(序列化)的顺序一致
  17.         //2. 否则会出现异常
  18.         System.out.println(ois.readInt());
  19.         System.out.println(ois.readBoolean());
  20.         System.out.println(ois.readChar());
  21.         System.out.println(ois.readDouble());
  22.         System.out.println(ois.readUTF());
  23.         //dog 的编译类型是 Object , dog 的运行类型是 Dog
  24.         Object dog = ois.readObject();
  25.         System.out.println("运行类型=" + dog.getClass());
  26.         System.out.println("dog信息=" + dog);//底层 Object -> Dog
  27.         //这里是特别重要的细节:
  28.         //1. 如果我们希望调用Dog的方法, 需要向下转型
  29.         //2. 需要我们将Dog类的定义,放在到可以引用的位置
  30.         Dog dog2 = (Dog)dog;
  31.         System.out.println(dog2.getName()); //旺财..
  32.         //关闭流, 关闭外层流即可,底层会关闭 FileInputStream 流
  33.         ois.close();
  34.     }
  35. }
复制代码
15.6打印流-PrintStream和PrintWriter

<img alt="image-20250901152321665" >
12.png
  1. package com.ming.printstream_;
  2. import java.io.IOException;
  3. import java.io.PrintStream;
  4. /**
  5. * @author ming
  6. * @version 1.0
  7. * 演示PrintStream (字节打印流/输出流)
  8. */
  9. public class PrintStream_ {
  10.     public static void main(String[] args) throws IOException {
  11.         PrintStream out = System.out;
  12.         //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
  13.         /*
  14.              public void print(String s) {
  15.                 if (s == null) {
  16.                     s = "null";
  17.                 }
  18.                 write(s);
  19.             }
  20.          */
  21.         out.println("我发到付的");
  22.         out.write("666".getBytes());
  23.         //因为print底层使用的是write , 所以我们可以直接调用write进行打印/输出
  24.         out.close();
  25.         //我们可以去修改打印流输出的位置/设备
  26.         //1. 输出修改成到 "D:\JAVA\韩顺平\代码\chapter19\1.txt"
  27.         //2. "hello, ming~" 就会输出到 D:\JAVA\韩顺平\代码\chapter19\1.txt
  28.         //3. public static void setOut(PrintStream out) {
  29.         //        checkIO();
  30.         //        setOut0(out); // native 方法,修改了out
  31.         //   }
  32.         System.setOut(new PrintStream("D:/JAVA/韩顺平/代码/chapter19/1.txt"));
  33.         System.out.println("hello, ming~");
  34.     }
  35. }
复制代码
15.7 Properties 类

15.7.1 看一个需求

com.ming.properties_ Properties01.java
如下一个配置文件 mysql.properties
  1. ip=192.168.0.13
  2. user=root
  3. pwd=12345
复制代码
请问编程读取 ip、user 和 pwd 的值是多少
√ 分析

  • 传统的方法
  • 使用Properties类可以方便实现
  1. public class Properties01 {
  2.     public static void main(String[] args) throws IOException {
  3.         //读取mysql.properties 文件,并得到ip, user 和 pwd
  4.         BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
  5.         String line = "";
  6.         while ((line = br.readLine()) != null) { //循环读取
  7.             String[] split = line.split("=");
  8.             //如果我们要求指定的ip值
  9.             if("ip".equals(split[0])) {
  10.                 System.out.println(split[0] + "值是: " + split[1]);
  11.             }
  12.         }
  13.         br.close();
  14.     }
  15. }
复制代码
15.7.2 基本介绍


  • 专门用于读写配置文件的集合类
    配置文件的格式:
    键=值
    键=值
  • 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String
  • Properties的常见方法

    • load:加载配置文件的键值对到Properties对象
    • list:将数据显示到指定设备
    • getProperty(key):根据键获取值
    • setProperty(key,value):设置键值对到Properties对象
    • store:将Properties中的键值对存储到配置文件,在Idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
      http://tool.chinaz.com/tools/unicode.aspx unicode码查询工具

15.7.3 应用案例


  • 使用Properties类完成对 mysql.properties 的读取,看演示
  • 使用Properties类添加key-val到新文件 mysql2.properties 中
  • 使用Properties类完成对 mysql2.properties 的读取,并修改某个key-val
  1. package com.ming.properties;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.Properties;
  6. /**
  7. * @author ming
  8. * @version 1.0
  9. */
  10. public class Properties02 {
  11.     public static void main(String[] args) throws IOException {
  12.         //使用Properties 类来读取mysql.properties 文件
  13.         //1. 创建Properties 对象
  14.         Properties properties = new Properties();
  15.         //2. 加载指定配置文件
  16.         properties.load(new FileReader("src/mysql.properties"));
  17.         //3. 把k-v显示控制台
  18.         properties.list(System.out);
  19.         //4. 根据key 获取对应的值
  20.         String user = properties.getProperty("user");
  21.         String pwd = properties.getProperty("pwd");
  22.         System.out.println("用户名=" + user );
  23.         System.out.println("密码是="  + pwd);
  24.     }
  25. }
复制代码
  1. package com.ming.properties;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.Properties;
  6. /**
  7. * @author ming
  8. * @version 1.0
  9. */
  10. public class Properties03 {
  11.     public static void main(String[] args) throws IOException {
  12.         //使用Properties 类来创建 配置文件, 修改配置文件内容
  13.         Properties properties = new Properties();
  14.         //创建
  15.         //1.如果该文件没有key 就是创建
  16.         //2.如果该文件有key ,就是修改
  17.         /*
  18.             Properties 父类是 Hashtable , 底层就是Hashtable 核心方法
  19.             public synchronized V put(K key, V value) {
  20.                 // Make sure the value is not null
  21.                 if (value == null) {
  22.                     throw new NullPointerException();
  23.                 }
  24.                 // Makes sure the key is not already in the hashtable.
  25.                 Entry<?,?> tab[] = table;
  26.                 int hash = key.hashCode();
  27.                 int index = (hash & 0x7FFFFFFF) % tab.length;
  28.                 @SuppressWarnings("unchecked")
  29.                 Entry<K,V> entry = (Entry<K,V>)tab[index];
  30.                 for(; entry != null ; entry = entry.next) {
  31.                     if ((entry.hash == hash) && entry.key.equals(key)) {
  32.                         V old = entry.value;
  33.                         entry.value = value;//如果key 存在,就替换
  34.                         return old;
  35.                     }
  36.                 }
  37.                 addEntry(hash, key, value, index);//如果是新k, 就addEntry
  38.                 return null;
  39.             }
  40.          */
  41.         properties.setProperty("charset","utf-8");
  42.         properties.setProperty("username","汤姆");
  43.         properties.setProperty("password","540088");
  44.         //将k-v 存储文件中即可
  45.         properties.store(new FileOutputStream("src\\mysql2.properties"),null);
  46.         System.out.println("保存配置文件成功~");
  47.     }
  48. }
复制代码
15.8 转换流(InputStreamReader与OutputStreamWriter)

转换流是字节流与字符流之间的桥梁,能在字节流操作过程中指定字符编码,有效解决中文乱码等问题。
15.8.1 InputStreamReader(字节流转字符流)

InputStreamReader 可将字节输入流(如 FileInputStream)转换为字符输入流,并指定字符编码(如 GBK、UTF-8 等),方便按指定编码读取字符数据。
示例代码(解决中文读取乱码问题)
  1. package com.ming.transformation;
  2. import java.io.*;
  3. /**
  4. * 演示使用 InputStreamReader 转换流解决中文乱码问题
  5. * 将字节流 FileInputStream 转成字符流 InputStreamReader,指定编码 UTF-8
  6. */
  7. public class InputStreamReader_ {
  8.     public static void main(String[] args) throws IOException {
  9.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\1.txt";
  10.         // 将 FileInputStream 转为 InputStreamReader,指定编码为 UTF-8
  11.         // 再将 InputStreamReader 传入 BufferedReader,利用缓冲提高读取效率
  12.         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
  13.         // 按行读取文件内容
  14.         String s = br.readLine();
  15.         System.out.println("读取内容=" + s);
  16.         // 关闭外层缓冲流,会自动关闭内层的转换流和字节流
  17.         br.close();
  18.     }
  19. }
复制代码
代码说明

  • 通过 new InputStreamReader(new FileInputStream(filePath), "UTF-8"),把字节输入流 FileInputStream 转换为指定 UTF-8 编码的字符输入流 InputStreamReader。
  • 结合 BufferedReader 进行缓冲读取,提升读取大文件时的性能,最后调用 readLine() 按行读取内容。
15.8.2 OutputStreamWriter(字符流转字节流)

OutputStreamWriter 能把字符输出流转换为字节输出流,同时指定字符编码,确保字符按指定编码写入到字节流(如文件)中。
示例代码(指定编码写入文件)
  1. package com.ming.transformation;
  2. import java.io.*;
  3. /**
  4. * 演示 OutputStreamWriter 使用
  5. * 把 FileOutputStream 字节流,转成字符流 OutputStreamWriter,指定处理的编码为 UTF-8
  6. */
  7. public class OutputStreamWriter_ {
  8.     public static void main(String[] args) throws IOException {
  9.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\1.txt";
  10.         String charSet = "UTF-8";
  11.         // 将 FileOutputStream 转为 OutputStreamWriter,指定编码为 UTF-8
  12.         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
  13.         // 结合 BufferedWriter 进行缓冲写入,提升写入性能
  14.         BufferedWriter bw = new BufferedWriter(osw);
  15.         bw.write("hi, 123346密密麻麻的");
  16.         bw.newLine(); // 写入换行符
  17.         bw.write("ming");
  18.         // 关闭缓冲流,会自动刷新并关闭内层的转换流和字节流
  19.         bw.close();
  20.         System.out.println("按照 " + charSet + " 保存文件成功~");
  21.     }
  22. }
复制代码
代码说明

  • 利用 new OutputStreamWriter(new FileOutputStream(filePath), charSet),将字节输出流 FileOutputStream 转换为指定 UTF-8 编码的字符输出流 OutputStreamWriter。
  • 借助 BufferedWriter 实现缓冲写入,newLine() 方法用于写入系统相关的换行符,让换行更具兼容性。
15.8.3 字符流默认编码问题与转换流的必要性

当直接使用字符流(如 FileReader)读取文件时,默认采用系统的字符编码(通常为 UTF-8,但不同环境可能有差异)。若文件编码与默认编码不一致,就会出现乱码。而转换流可显式指定编码,避免该问题。
示例代码(直接用 FileReader 可能出现乱码的情况)
  1. package com.ming.transformation;
  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. /**
  6. * 演示直接使用 FileReader 可能出现的编码问题
  7. */
  8. public class CodeQuestion {
  9.     public static void main(String[] args) throws IOException {
  10.         String filePath = "D:\\JAVA\\韩顺平\\代码\\chapter19\\2.txt";
  11.         // 直接使用 FileReader,默认采用系统编码(若文件编码非系统编码,可能乱码)
  12.         BufferedReader br = new BufferedReader(new FileReader(filePath));
  13.         String s = br.readLine();
  14.         System.out.println("读取到的内容: " + s);
  15.         br.close();
  16.     }
  17. }
复制代码
说明
若 2.txt 文件的编码不是系统默认编码(比如文件是 GBK 编码,而系统默认是 UTF-8),使用 FileReader 读取就会出现中文乱码。此时,就需要用 InputStreamReader 并指定 GBK 编码来正确读取。
15.8.4 转换流的扩展应用场景


  • 多编码文件处理:在需要处理不同编码的文件(如同时处理 GBK 和 UTF-8 编码的配置文件)时,可通过转换流灵活指定编码,统一处理逻辑。
  • 网络流编码转换:当从网络获取字节流数据(如 HTTP 响应体),且已知数据编码时,用 InputStreamReader 转换为字符流并指定编码,能方便地处理文本内容。
  • 日志文件编码统一:若应用生成的日志文件需要按特定编码(如 UTF-8)存储,可通过 OutputStreamWriter 指定编码,将日志内容正确写入文件。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册