File类和IO流

打印 上一主题 下一主题

主题 571|帖子 571|积分 1713

File类和IO流

File类

概述

  • public class File
  • 文件和目录路径名的抽象表示
  • 文件和目录是可以通过File封装成对象的
  • 封装的不是文件,而是一个路径(可以存在,也可以不存在);要通过具体的操作将这个路径转化为具体存在

  1. public class FileDemo {
  2.     public static void main(String[] args) {
  3.         //创建一个路径操作对象 路径包括父路径和子路径
  4.         File f = new File("G:\\FileTest\\java.txt");
  5.         System.out.println(f);
  6.         //创建一个路径操作对象 父路径,子路径
  7.         File f1 = new File("G:\\FileTest","java.txt");
  8.         System.out.println(f1);
  9.         //创建一个父路径操作对象
  10.         File f2 = new File("G:\\FileTest");
  11.         //从父路径和子路径创建的路径操作对象
  12.         File f3 = new File(f2,"java.txt");
  13.         System.out.println(f3);
  14.     }
  15. }
复制代码
运行结果:
  1. //File类重写了toString()
  2. G:\FileTest\java.txt
  3. G:\FileTest\java.txt
  4. G:\FileTest\java.txt
复制代码
File类创建功能

运行代码之前

代码
  1. public class FileDemo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         /*在G:\FileTest目录下,创建一个Hello.txt文件
  4.         如果文件不存在就创建文件,返回true
  5.         如果文件存在返回false*/
  6.         File f1 = new File("G:\\FileTest\\Hello.txt");
  7.         System.out.println(f1.createNewFile());
  8.         /*在G:\FileTest目录下,创建一个Cat文件夹
  9.         如果文件不存在就创建文件,返回true
  10.         如果文件存在返回false*/
  11.         File f2 = new File("G:\\FileTest\\Cat");
  12.         System.out.println(f2.mkdir());
  13.         /*在G:\FileTest目录下,创建一个多级目录Eat\egg文件夹
  14.         如果文件不存在就创建文件,返回true
  15.         如果文件存在返回false*/
  16.         File f3 = new File("G:\\FileTest\\Eat\\egg");
  17.         System.out.println(f3.mkdirs());
  18.     }
  19. }
复制代码
运行结果
  1. true
  2. true
  3. true
复制代码


注意

  • 如果同一目录下存在同名的文件夹,createNewFile()创建文件时会失败;要将同名的文件夹删掉才会创建文件成功。
File类判断和获取功能

运行代码之前,先在此位置创建一个java.txt文件

  1. public class FileDemo2 {
  2.     public static void main(String[] args) {
  3.         //创建File对象
  4.         File f = new File("idea_test\\java.txt");
  5.         //抽象路径名表示的File是否为目录
  6.         System.out.println("是否为目录:"+f.isDirectory());
  7.         //抽象路径名表示的File是否为文件
  8.         System.out.println("是否为文件:"+f.isFile());
  9.         //抽象路径名表示的File是否存在
  10.         System.out.println("是否存在:"+f.exists());
  11.         //返回此抽象路径名的绝对路径(字符串)
  12.         System.out.println("绝对路径:"+f.getAbsolutePath());
  13.         //将此抽象路径名转化为字符串
  14.         System.out.println("抽象路径:"+f.getPath());
  15.         //返回此抽象路径名表示的文件名或者目录名
  16.         System.out.println("文件名或者目录名:"+f.getName());
  17.         System.out.println("-------FileTest目录-------------");
  18.         File f1 = new File("G:\\FileTest");
  19.         //返回此抽象路径名表示的目录中的文件名和目录的名称字符串数组
  20.         String[] list = f1.list();
  21.         //遍历字符串数组
  22.         for (String s : list) {
  23.             System.out.println(s);
  24.         }
  25.         System.out.println("---------FileTest目录中的文件-----------");
  26.         //返回此抽象路径名表示的目录中的文件名和目录的File对象数组
  27.         File[] files = f1.listFiles();
  28.         for (File file : files) {
  29.             //System.out.println(file);
  30.             //如果对象是一个文件,输出文件名
  31.             if (file.isFile()){
  32.                 System.out.println(file.getName());
  33.             }
  34.         }
  35.     }
  36. }
复制代码
运行结果:
  1. 是否为目录:false
  2. 是否为文件:true
  3. 是否存在:true
  4. 绝对路径:G:\Work_Basic\JavaSE_Code\idea_test\java.txt
  5. 抽象路径:idea_test\java.txt
  6. 文件名或者目录名:java.txt
  7. -------FileTest目录-------------
  8. Cat
  9. Eat
  10. Hello.txt
  11. java.txt
  12. ---------FileTest目录中的文件-----------
  13. Hello.txt
  14. java.txt
复制代码
File类删除功能

创建一个hello.txt文件
  1. public class FileDemo3 {
  2.     public static void main(String[] args) throws IOException {
  3.         //在当前模块目录下创建一个hello.txt文件
  4.         File f = new File("idea_test\\hello.txt");
  5.         //System.out.println(f.createNewFile());
  6.         //删除当前模块目录下的hello.txt文件
  7.         System.out.println(f.delete());
  8.     }
  9. }
复制代码
运行结果:hello.txt文件已经删除
  1. true
复制代码
  1. //在当前模块目录下创建一个"雀巢"文件夹
  2. File f1 = new File("idea_test\\雀巢");
  3. System.out.println(f1.mkdir());
复制代码
运行结果:true
  1. //删除当前模块目录下的"雀巢"文件夹
  2. System.out.println(f1.delete());
复制代码
运行结果:true
  1. //在当前模块目录下创建一个"雀巢"文件夹,文件夹里有个java.txt文件
  2. File f2 = new File("idea_test\\雀巢");
  3. System.out.println(f2.mkdir());
  4. File f3 = new File(f2, "java.txt");
  5. System.out.println(f3.createNewFile());
复制代码
运行结果:
  1. true
  2. true
复制代码

创建多级目录文件

  • 在创建文件之前,应该先创建上一级的目录,否则会报错
  1. //删除当前模块目录下的"雀巢"文件夹
  2. System.out.println(f3.delete());
  3. System.out.println(f2.delete());
复制代码
运行结果:"雀巢"文件夹删掉了
  1. true
  2. true
复制代码

删除文件夹

  • 如果要删除的文件夹下有文件,删除操作会不成功,返回false
  • 要先删除该文件夹下的文件,之后才能删除该文件夹
递归

方法中调用方法本身
思路:把一个复杂的问题,层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算。
  1. public class Demo {
  2.     public static void main(String[] args) {
  3.         /*不死神兔:求第20个月兔子的对数
  4.          * 每个月兔子的对数:1,1,2,3,5,8……*/
  5.         //创建长度为20的数组 索引0-19
  6.         int[] arr = new int[20];
  7.         //第一个月:1对
  8.         arr[0] = 1;
  9.         //第二个月:1对
  10.         arr[1] = 1;
  11.         //从第三个月(索引2)开始:兔子的对数等于前两个月之和
  12.         for (int i = 2; i < arr.length; i++) {
  13.             arr[i] = arr[i - 1] + arr[i - 2];
  14.         }
  15.         //输出第20个月(索引19)兔子的对数
  16.         System.out.println(arr[19]);
  17.     }
  18. }
复制代码
运行结果:
  1. 6765
复制代码
使用递归来解决上述问题
  1. public class Demo {
  2.     public static void main(String[] args) {
  3.         /*不死神兔:求第20个月兔子的对数
  4.          * 每个月兔子的对数:1,1,2,3,5,8……*/
  5.         //第20个月,兔子的对数
  6.         System.out.println(f(20));
  7.     }
  8.     /**
  9.      * 递归:求第n个月兔子的对数
  10.      *
  11.      * @param n 第n个月
  12.      * @return 兔子的对数
  13.      * StackOverflowError  当由于应用程序而发生堆栈溢出时引发 递归太深。递归需要停止
  14.      */
  15.     public static int f(int n) {
  16.         if (n == 1 || n == 2) {
  17.             return 1;
  18.         } else {
  19.             //从第3个月开始,每个月兔子的对数都是前两个月之和
  20.             return f(n - 1) + f(n - 2);
  21.         }
  22.     }
  23. }
复制代码
运行结果:
  1. 6765
复制代码
递归解决问题

  • 递归出口:否则会出现内存溢出StackOverflowError
  • 递归规则:与原问题相似的规模较小的问题
案例:递归求5的阶乘
  1. public class Demo {
  2.     public static void main(String[] args) {
  3.         //调用方法,求5的阶乘
  4.         System.out.println(f(5));
  5.     }
  6.     /**
  7.      * 阶乘
  8.      * @param n
  9.      * @return
  10.      */
  11.     public static int f(int n) {
  12.         if (n == 1) {
  13.             return 1;
  14.         } else {
  15.             return n * f(n - 1);
  16.         }
  17.     }
  18. }
复制代码
运行结果:
  1. 120
复制代码
IO字节流

IO流概述

  • IO:输入/输出
  • 流:数据传输
  • IO流就是处理设备之间数据传输问题的(常见:文件复制,文件上传,文件下载)
输入:读数据;硬盘到内存条
输出:写数据;内存条到硬盘
IO流的分类

  • 按照数据的流向


  • 输入流:读数据
  • 输出流:写数据

  • 按照数据类型


  • 字节流:字节输入流,字节输出流
  • 字符流:字符输入流,字符输出流
使用场景

  • 用记事本打开,能看懂的内容,使用字符流,否则使用字节流。
  • 如果不知道该使用哪种类型的流,就使用字节流。
字节流写数据
字节流抽象基类

  • public abstract class InputStream:字节输入流的所有类的超类
  • public abstract class OutputStream:字节输出流的所有类的超类
  • 子类名称特点:子类名称都是以父类名作为子类命的后缀
FileOutputStream:文件输入流,用于将数据写入File

  • FileOutputStream(String name):将数据以指定的名称写入文件
使用字节输出流写数据的步骤

  • 创建字节输出流对象


  • 调用系统功能创建了文件
  • 创建字节输出流
  • 让字节数流对象指向文件)

  • 调用字节输出流对象的写数据方法
  • 释放资源:关闭此文件的输出流并释放与此流关联的任何系统资源
创建字节输出流对象的三种方式:
  1. //创建字节输出流对象        第一种
  2. FileOutputStream fo = new FileOutputStream("idea_test\\java.txt");
复制代码
  1. //创建字节输出流对象        第二种
  2. File file = new File("idea_test\\java.txt");
  3. FileOutputStream fo = new FileOutputStream(file);
复制代码
  1. //创建字节输出流对象        第三种
  2. FileOutputStream fo = new FileOutputStream(new File("idea_test\\java.txt"));
复制代码
案例:使用字节输出流写数据的步骤
  1. public class IoDemo {
  2.     public static void main(String[] args) throws IOException {
  3.         /**
  4.          * 创建字节输出流对象
  5.          * 1.调用系统功能创建了文件
  6.          * 2.创建了字节输出流对象
  7.          * 3.让字节输出流对象指向创建好的文件
  8.          */
  9.         FileOutputStream fo = new FileOutputStream("idea_test\\java.txt");
  10.         //void write(int b):将指定的字节写入此文件输出流
  11.         fo.write(97);
  12.         //释放资源:关闭此文件的输出流并释放与此流关联的任何系统资源
  13.         fo.close();
  14.     }
  15. }
复制代码
运行结果:

字节流写数据的三种方式
  1. //写入abcde        第一种
  2. fo.write(97);
  3. fo.write(98);
  4. fo.write(99);
  5. fo.write(100);
  6. fo.write(101);
复制代码
  1. //写入abcde        第二种
  2. byte[] b = {97,98,99,100,101};
  3. //或者,返回字符串中的字节数组
  4. //byte[] b = "abcde".getBytes();
  5. fo.write(b);
复制代码
  1. //写入abcde        第三种
  2. byte[] b = {97,98,99,100,101};
  3. //参数:字节数组   索引起始位置    索引结束位置
  4. fo.write(b,0,b.length);
复制代码
字节流写数据的两个小问题

  • 字节流写数据如何实现换行?


  • Windows: \r\n
  • Linux: \n        (win11用这个也可以)
  • Mac: \r

  • 字节流写数据如何实现追加写入?


  • public FileOutputStream​(File file, boolean append)
  1. //追加写入
  2. public class IoDemo {
  3.     public static void main(String[] args) throws IOException {
  4.         //如果第二个参数为true,将在文件末尾追加内容
  5.         //如果第二个参数不为true(不写或者false),将不是追加,而是从文件开头开始覆盖内容
  6.         FileOutputStream fo = new FileOutputStream("idea_test\\java.txt",true);
  7.         //FileOutputStream fo = new FileOutputStream("idea_test\\java.txt",false);
  8.         //写入十次”hello“
  9.         for (int i = 0; i < 10; i++) {
  10.             // 写入字节流
  11.             // getBytes()返回字符串中的字节数组
  12.             fo.write("hello".getBytes());
  13.             fo.write("\n".getBytes());
  14.         }
  15.         fo.close();
  16.     }
  17. }
复制代码
字节流写数据加异常处理
  1. public class IoDemo {
  2.     public static void main(String[] args) {
  3.         //初始化为null
  4.         FileOutputStream fo = null;
  5.         try {
  6.             //可能出现异常的代码
  7.             fo = new FileOutputStream("idea_test\\java.txt");
  8.             fo.write("世界杯".getBytes());
  9.         } catch (IOException e) {
  10.             //异常处理的代码
  11.             e.printStackTrace();
  12.         } finally {//被finally控制的语句,一定会执行,除非JVM退出
  13.             //null调方法会报空指针异常,所以fo不为null才能执行close()释放资源操作
  14.             if (fo != null) {
  15.                 try {
  16.                     //close()有编译时异常,用try...catch()处理一下
  17.                     fo.close();
  18.                 } catch (IOException e) {
  19.                     e.printStackTrace();
  20.                 }
  21.             }
  22.         }
  23.     }
  24. }
复制代码
字节流读数据(一次读一个字节)
FileInputStream:从文件系统中的文件获取输入字节

  • FileInputStream(String name):通过打开与实际文件的连接来创建一个FileInputStream,该文件由文件系统中的路径名name命名。
使用字节输入流读数据的步骤:

  • 创建字节输入流对象
  • 调用字节输入流对象的读数据方法
  • 释放资源
一次读取一个字节        read(),如果返回-1说明到了文件末尾
  1. public class IoDemo {
  2.     public static void main(String[] args) {
  3.         //需求:把文件java.txt中的内容读取出来在控制台输出
  4.         File file = new File("idea_test\\java.txt");
  5.         //初始化fi
  6.         FileInputStream fi = null;
  7.         try {
  8.             //创建字节输出流对象
  9.             fi = new FileInputStream(file);
  10.             //调用字节输入流对象的读数据方法,一次读取一个字节
  11.             int read;
  12.             while ((read = fi.read()) != -1) {
  13.                 //输出
  14.                 System.out.print((char) read);
  15.             }
  16.             //释放资源
  17.         } catch (IOException e) {
  18.             e.printStackTrace();
  19.         } finally {
  20.             if (fi != null) {
  21.                 try {
  22.                     fi.close();
  23.                 } catch (IOException e) {
  24.                     e.printStackTrace();
  25.                 }
  26.             }
  27.         }
  28.     }
  29. }
复制代码
再补充一个一次性读取文件全部内容的:
  1. public class IoDemo {//throws抛出异常
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:把文件java.txt中的内容读取出来在控制台输出
  4.         File file = new File("idea_test\\java.txt");
  5.         //创建文件输入流对象
  6.         FileInputStream fi = new FileInputStream(file);
  7.         //file.length()返回值是long,但byte只能装整形大小的空间,所以要强转
  8.         byte[] buffer = new byte[(int) file.length()];
  9.         //调用字节输入流对象的读数据方法,读取文件全部内容
  10.         fi.read(buffer);
  11.         System.out.print(new String(buffer));
  12.         //释放资源
  13.         fi.close();
  14.     }
  15. }
复制代码
注意:文件字节流读取文件,一次读一个字节,遇到中文会乱码;一次读取文件的所有内容,中文不会乱码。
字节流复制文本文件
思路:

  • 根据数据源创建字节输入流对象
  • 根据目的地创建字节输出流对象
  • 读写数据,复制文本文件
  • 释放资源
  1. public class IoDemo {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:把文件G:\FileTest\Hello.txt中的内容复制到模块目录下的java.txt
  4.         //1.根据数据源创建输入流对象
  5.         InputStream fo = new FileInputStream("G:\\FileTest\\Hello.txt");
  6.         //2.根据目的地创建输出流对象
  7.         OutputStream fi = new FileOutputStream("idea_test\\java.txt");
  8.         //一次读取一个字节,一次写入一个字节
  9.         //3.读文件
  10.         int read;
  11.         while ((read = fo.read()) != -1) {
  12.             //4.写入文件
  13.             fi.write(read);
  14.         }
  15.         //5.释放资源,先关闭输出流,在关闭输入流
  16.         fo.close();
  17.         fi.close();
  18.     }
  19. }
复制代码
字节流读数据(一次读一个字节数组)
使用字节输入流读数据的步骤

  • 创建字节输入流对象
  • 调用字节输入流对象的读数据方法
  • 释放资源
  1. public class IoDemo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //创建字节输入流对象
  4.         InputStream fo = new FileInputStream("idea_test\\java.txt");
  5.         //创建一个字节数组,长度一般为1024及其整数倍
  6.         byte[] bytes = new byte[1024];
  7.         //创建字节输入流对象的读数据方法,
  8.         // len 一次读取的字节数组的长度
  9.         int len;
  10.         while ((len = fo.read(bytes)) != -1) {
  11.             System.out.print(new String(bytes, 0, len));
  12.         }
  13.         //释放资源
  14.         fo.close();
  15.     }
  16. }
复制代码
注意:读含有中文的文件时,建议一次读完。
因为一个汉字占2~3个字节,如果正好读了半个汉字,那就乱码了(如图)。

后面的内容用字符流就更方便了,因为一个汉字一个字母都是一个字符。
字节流复制图片
思路

  • 根据数据源创建字节输入流对象
  • 根据目的地创建字节输出流对象
  • 读写数据,复制图片
  • 释放资源
  1. public class IoDemo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:把图片G:\FileTest\dog.jpg复制到模块目录下的dog.jpg
  4.         //1.根据数据源创建输入流对象
  5.         InputStream fo = new FileInputStream("G:\\FileTest\\dog.jpg");
  6.         //2.根据目的地创建输出流对象
  7.         OutputStream fi = new FileOutputStream("idea_test\\dog.jpg");
  8.         //定义一个字节数组
  9.         byte[] bytes = new byte[1024];
  10.         //一次读取一个字节数组,一次写入一个字节数组
  11.         int len;
  12.         //3.循环读写图片
  13.         while ((len = fo.read(bytes)) != -1) {
  14.             //4.写入文件
  15.             fi.write(bytes,0,len);
  16.         }
  17.         //5.释放资源,先关闭输出流,在关闭输入流
  18.         fo.close();
  19.         fi.close();
  20.     }
  21. }
复制代码
运行结果:

IO字符流

字节缓冲流

字节缓冲输出流写数据
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.             //字节缓冲输出流写数据
  4.         //创建字节缓冲输出流
  5.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("idea_test\\java.txt"));
  6.         //写入数据
  7.         bos.write("hello\r\n".getBytes());
  8.         bos.write("java\r\n".getBytes());
  9.         //释放资源
  10.         bos.close();
  11.     }
  12. }
复制代码
字节缓冲输入流读数据
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.             //字节缓冲输入流读数据
  4.         //创建字节缓冲输入流,一次性从文件中读取8192个字节
  5.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream("idea_test\\java.txt"));
  6.         //一次读取的字节流数组长度
  7.         //每次读取的1024个字节,是直接从字节缓冲流那8192个字节里拿的,拿完之后字节缓冲流会再次从文件中一次性读取8192个字节
  8.         byte[] bytes = new byte[1024];
  9.         //读数据
  10.         int len;
  11.         while ((len = bis.read(bytes)) != -1) {
  12.             System.out.print(new String(bytes,0,len));
  13.         }
  14.         //释放资源
  15.         bis.close();
  16.     }
  17. }
复制代码
字节流复制视频
思路

  • 根据数据源创建字节输入流对象
  • 根据目的地创建字节输出流对象
  • 读写数据,复制视频
  • 释放资源
字节缓冲流一次读写一个字节数组
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //把G:\FileTest\video.avi复制到模块目录下idea_test\video.avi
  4.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream("G:\\FileTest\\video.avi"));
  5.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("idea_test\\video.avi"));
  6.         byte[] bytes = new byte[1024];
  7.         int len;
  8.         while ((len = bis.read(bytes)) != -1) {
  9.             bos.write(bytes,0,len);
  10.             //System.out.println(new String(bytes,0,len));
  11.         }
  12.         bos.close();
  13.         bis.close();
  14.     }
  15. }
复制代码
速度:

  • 基本字节流一次读写一个字节 < 基本字节流一次读写一个字节数组 < 字节缓冲流一次读写一个字节 < 字节缓冲流一次读写一个字节数组
为什么出现字符流

  • 字节流操作中文不方便,所以Java提供了字符流


  • 字符流 = 字节流 + 编码表

  • 用字节流每次读写一个字节复制文本时,底层操作会自动进行字节拼接中文
  • 汉字在存储的时候,无论选择哪种编码格式,第一个字节都是负数
案例:
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         String  s = "abc";
  4.         byte[] bytes = s.getBytes("UTF-8");
  5.         byte[] bytes1 = s.getBytes("GBK");
  6.         //[97, 98, 99]
  7.         System.out.println(Arrays.toString(bytes));
  8.         //[97, 98, 99]
  9.         System.out.println(Arrays.toString(bytes1));
  10.         String  s1 = "肥胖";
  11.         byte[] bytes2 = s1.getBytes("UTF-8");
  12.         byte[] bytes3 = s1.getBytes("GBK");
  13.         //[-24, -126, -91, -24, -125, -106]
  14.         System.out.println(Arrays.toString(bytes2));
  15.         //[-73, -54, -59, -42]
  16.         System.out.println(Arrays.toString(bytes3));
  17.     }
  18. }
复制代码
编码表

  • 计算机存储数据是二进制的(0和1)
  • 编码和解码


  • 按照规则,将字符存储到计算机中,称为编码;反之,将存储到计算机中的二进制内容按照规则解析显示出来,称为解码

  • 编码和解码的规则必须一致,否则会出现乱码
  • 字符编码


  • 就是一套自然语言的字符与二进制数之间的对应关系。如(A,65)
字符集

  • 是一个系统支持的所有字符集的集合,包括各国家文字,标点符号,图形符号,数字等
  • 计算机要存储和识别各种字符集符号,就要进行字符编码,一套字符集必然至少有一套字符编码规则。常见的字符集有ASCII字符集,GBXXX字符集,Unicode字符集等



字符串中的编码解码问题
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         String s = "接化发";
  4.         //默认规则编码
  5.         byte[] bys = s.getBytes();
  6.         System.out.println(Arrays.toString(bys));
  7.         //指定规则编码
  8.         byte[] bys1 = s.getBytes("GBK");
  9.         System.out.println(Arrays.toString(bys1));
  10.         //默认规则解码
  11.         String s1 = new String(bys);
  12.         System.out.println(s1);
  13.         //指定规则解码
  14.         String s2 = new String(bys1, "GBK");
  15.         System.out.println(s2);
  16.     }
  17. }
复制代码
运行结果:
  1. [-26, -114, -91, -27, -116, -106, -27, -113, -111]
  2. [-67, -45, -69, -81, -73, -94]
  3. 接化发
  4. 接化发
复制代码
字符流中的编码解码问题
字符流抽象基类

  • Reader:字符输入流的抽象类
  • Writer:字符输出流的抽象类
InputStreamReader:是从字节流到字符流的桥梁
OutputStreamWriter:是从字符流到字节流的桥梁
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //字符输出流对象   默认编码格式
  4.         //OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("idea_test\\java.txt"));
  5.         //字符输出流对象   指定编码格式
  6.         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("idea_test\\java.txt"),"UTF-8");
  7.         osw.write("蔬菜");
  8.         osw.close();
  9.         //字符输入流对象        指定编码格式
  10.         InputStreamReader isr = new InputStreamReader(new FileInputStream("idea_test\\java.txt"),"UTF-8");
  11.         
  12.                 //一次读取一个字符
  13.         int ch;
  14.         while ((ch = isr.read()) != -1) {
  15.             System.out.print((char)ch);
  16.         }
  17.         isr.close();
  18.     }
  19. }
复制代码
字符流写数据的5种方式

flush()和close()的区别

  • flush()刷新流,刷新之后还可以写数据
  • close()关闭流,关闭流之前会自动执行刷新流操作,关闭之后就不能再继续写数据了
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("idea_test\\java.txt"));
  4.         osw.write(97);
  5.         /**
  6.          * 刷新缓冲
  7.          * 字符流写数据如果不刷新流,那么数据就在缓冲区中,没close()之前,打开文件java.txt看不到数据
  8.          * 字符流相对于字节流是有缓冲的,真正写数据是字节流
  9.          */
  10.         osw.flush();
  11.         //close():关闭流之前会自动执行刷新流操作
  12.         //flush()刷新流之后还可以继续写数据,但是close()关闭流之后就不能继续写数据了
  13.         osw.close();
  14.     }
  15. }
复制代码
字符流写数据的5种方式:
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("idea_test\\java.txt"));
  4.         //1.写入一个字符:a
  5.         osw.write(97);
  6.         //2.写入一个字符数组:abcde
  7.         char[] chs = {'a', 'b', 'c', 'd', 'e'};
  8.         osw.write(chs);
  9.         //3.写入一个字符数组的一部分:abc
  10.         osw.write(chs, 0, 3);
  11.         //4.写入一个字符串:世界杯
  12.         String s = "世界杯";
  13.         osw.write(s);
  14.         //5.写入一个字符串的一部分:界
  15.         osw.write(s,1,1);
  16.         osw.flush();
  17.         osw.close();
  18.     }
  19. }
复制代码
字符流读数据的2种方式
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //创建字符输入流对象
  4.         InputStreamReader isr = new InputStreamReader(new FileInputStream("idea_test\\java.txt"));
  5.         //1.一次读一个字符
  6.         int ch;
  7.         while ((ch = isr.read()) != -1) {
  8.             System.out.print((char) ch);
  9.         }
  10.         //2.一次读取一个字符数组
  11.         char[] chs = new char[1024];
  12.         int len;
  13.         while ((len = isr.read(chs)) != -1) {
  14.             System.out.print(new String(chs,0,len));
  15.         }
  16.         isr.close();
  17.     }
  18. }
复制代码
字符流复制Java文件
思路:

  • 根据数据源创建字符输入流对象
  • 根据目的地创建字符输出流对象
  • 读写数据,复制文件
  • 释放资源
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:将模块下的idea_test\java.txt,复制到idea_test\java1.txt
  4.         //创建字符输入流对象
  5.         InputStreamReader isr = new InputStreamReader(new FileInputStream("idea_test\\java.txt"));
  6.         //创建字符输出流对象
  7.         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("idea_test\\java1.txt"));
  8.         //读写数据,复制文件
  9.         char[] chs = new char[1024];
  10.         int len;
  11.         while ((len = isr.read(chs)) != -1) {
  12.             osw.write(chs,0,len);
  13.         }
  14.         osw.close();
  15.         isr.close();
  16.     }
  17. }
复制代码
字符流复制Java文件(改进版)

思路:

  • 根据数据源创建字符输入流对象
  • 根据目的地创建字符输出流对象
  • 读写数据,复制文件
  • 释放资源
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:将模块下的idea_test\java.txt,复制到idea_test\java1.txt
  4.         //创建字符输入流对象
  5.         FileReader fr = new FileReader("idea_test\\java.txt");
  6.         //创建字符输出流对象
  7.         FileWriter fw = new FileWriter("idea_test\\java2.txt");
  8.         //读写数据,复制文件
  9.         char[] chs = new char[1024];
  10.         int len;
  11.         while ((len = fr.read(chs)) != -1) {
  12.             fw.write(chs,0,len);
  13.         }
  14.         fw.close();
  15.         fr.close();
  16.     }
  17. }
复制代码
字符缓冲流

构造方法

  • BufferedWriter(Writer out)
  • BufferedReader(Reader in)
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java.txt"));
  4.         bw.write("hello\n");
  5.         bw.write("world\r");
  6.         bw.write("java\r\n");
  7.         bw.write(97);
  8.         bw.write(98);
  9.         bw.write(99);
  10.         bw.close();
  11.         //缓冲流默认一次从文件里读取8192个字符
  12.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java1.txt"));
  13.         //每次读取的1024个字符,是直接从缓冲流那8192个字符里拿的,拿完之后缓冲流会再次从文件中一次性读取8192个字符
  14.         char[] chs = new char[1024];
  15.         int len;
  16.         while ((len = br.read(chs)) != -1){
  17.             System.out.println(new String(chs, 0, len));
  18.         }
  19.         br.close();
  20.     }
  21. }
复制代码
换行

  • /r Mac
  • /n Unix/Linux
  • /r/n Windows
  • 不过我在windows11上测试换行,以上三种都可以。
字符缓冲流复制Java文件
思路:

  • 根据数据源创建字符缓冲输入流对象
  • 根据目的地创建字符缓冲输出流对象
  • 读写数据,复制文件
  • 释放资源
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:java字符缓冲流复制文件,从idea_test\java.txt复制到idea_test\java3.txt
  4.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  5.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java3.txt"));
  6.         char[] chs = new char[1024];
  7.         int len;
  8.         while ((len = br.read(chs)) != -1){
  9.             bw.write(chs,0,len);
  10.         }
  11.         bw.close();
  12.         br.close();
  13.     }
  14. }
复制代码
字符缓冲流特有功能

newLine():就是根据系统,自动识别的换行符
readLine():一次读一行数据,如果读到了结尾则返回null;只读每行的内容,不读行尾终止符
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //写数据
  4.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java.txt"));
  5.         for (int i = 0; i < 10; i++) {
  6.             bw.write("hello-"+i);
  7.             //换行
  8.             bw.newLine();
  9.             bw.flush();
  10.         }
  11.         bw.close();
  12.         //读数据
  13.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  14.         String s;
  15.         while ((s = br.readLine()) != null){
  16.             System.out.println(s);
  17.         }
  18.         br.close();
  19.     }
  20. }
复制代码
字符缓冲流特有功能复制Java文件
思路:

  • 根据数据源创建字符缓冲输入流对象
  • 根据目的地创建字符缓冲输出流对象
  • 读写数据,复制文件(使用字符缓冲流特有功能)
  • 释放资源
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:java字符缓冲流(特有功能)复制文件,从idea_test\java.txt复制到idea_test\java3.txt
  4.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  5.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java4.txt"));
  6.         char[] chs = new char[1024];
  7.         String s;
  8.         while ((s = br.readLine())!=null){
  9.             //每写一行数据,换行,刷新
  10.             bw.write(s);
  11.             bw.newLine();
  12.             bw.flush();
  13.         }
  14.         bw.close();
  15.         br.close();
  16.     }
  17. }
复制代码
IO流小结
1.字节流


字节流小结

  • 字节流可以复制【任意文件】数据,有四种方式,一般采用字节缓冲流一次读写一个字节数组的方式
2.字符流


字符流小结

  • 字符流只能复制【文本数据】,有五种方式,一般采用字符缓冲流的特有功能
IO练习

1.集合到文件
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:将ArrayList集合中的字符串数据写入到文本文件。要求每一个字符串元素作为文件中的一行数据
  4.         //1.创建ArrayList集合
  5.         ArrayList<String> list = new ArrayList<>();
  6.         //2.向集合中创建字符串元素
  7.         list.add("hello");
  8.         list.add("world");
  9.         list.add("java");
  10.         list.add("世界杯");
  11.         //3.创建字符缓冲流输入对象
  12.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java.txt"));
  13.         //4.遍历集合,得到每一个字符串数据
  14.         for (String s : list) {
  15.             //5.调用字符缓冲流对象的方法写数据
  16.             bw.write(s);
  17.             bw.newLine();
  18.             bw.flush();
  19.         }
  20.         //6.释放资源
  21.         bw.close();
  22.     }
  23. }
复制代码
运行结果:

2.文件到集合
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:把文本文件中的数据读取到集合中,并遍历集合。要求:文本中每一行数据是一个集合元素
  4.         //1.创建字符缓冲输入流对象
  5.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  6.         //2.创建ArrayList集合
  7.         ArrayList<String> list = new ArrayList<>();
  8.         //3.调用字符缓冲输入流对象的方法读数据
  9.         String s;
  10.         while ((s = br.readLine()) != null) {
  11.             //4.把读到的字符串数据存储到集合
  12.             list.add(s);
  13.         }
  14.         //5.释放资源
  15.         br.close();
  16.         //6.遍历集合
  17.         for (String s1 : list) {
  18.             System.out.println(s1);
  19.         }
  20.     }
  21. }
复制代码
运行结果:
  1. hello
  2. world
  3. java
  4. 世界杯
复制代码
3.点名器
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:文件中存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名
  4.         //1.创建字符缓冲输入流对象
  5.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  6.         //2.创建ArrayList集合
  7.         ArrayList<String> list = new ArrayList<>();
  8.         //3.调用字符缓冲输入流对象的方法读数据
  9.         String line;
  10.         while ((line = br.readLine()) != null) {
  11.             //4.把读到的字符串数据存储到集合
  12.             list.add(line);
  13.         }
  14.         //5.释放资源
  15.         br.close();
  16.         //6.使用Random产生一个随机数,随机数的范围在:[0,集合长度)
  17.         Random random = new Random();
  18.         int i = random.nextInt(list.size());
  19.         //7.把产生的随机数作为索引,在集合中获取值
  20.         String s = list.get(i);
  21.         //8.将获取到的值输出到控制台
  22.         System.out.println(s);
  23.     }
  24. }
复制代码
4.集合到文件(改进版)
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //需求:将ArrayList集合中的学生数据写入到文本文件。要求每一个向何生对象的数据作为文件中的一行数据
  4.         //格式:学号,姓名,年龄,居住地
  5.         //1.定义学生类
  6.         //2.创建ArrayList集合
  7.         ArrayList<Student> list = new ArrayList<>();
  8.         //3.创建学生对象
  9.         Student s1 = new Student("初二001", "小明", 15, "西安");
  10.         Student s2 = new Student("初二002", "小红", 16, "北京");
  11.         Student s3 = new Student("初二003", "小军", 17, "上海");
  12.         Student s4 = new Student("初二004", "白展堂", 14, "云南");
  13.         Student s5 = new Student("初二005", "史珍香", 13, "广州");
  14.         //4.把学生对象添加到集合中
  15.         list.add(s1);
  16.         list.add(s2);
  17.         list.add(s3);
  18.         list.add(s4);
  19.         list.add(s5);
  20.         //5.创建字符缓冲输出流对象
  21.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java.txt"));
  22.         //6.遍历集合,得到每一个学生对象
  23.         for (Student stu : list) {
  24.             //7.把学生对象的数据拼接成指定格式的字符串
  25.             StringBuffer sb = new StringBuffer();
  26.             sb.append(stu.getId() + "," + stu.getName() + "," + stu.getAge() + "," + stu.getAddress());
  27.             //8.调用字符缓冲输出流对象的方法写数据
  28.             bw.write(sb.toString());
  29.             bw.newLine();
  30.             bw.flush();
  31.         }
  32.         //9.释放资源
  33.         bw.close();
  34.     }
  35. }
复制代码
5.文件到集合(改进版)
  1. public class Demo3 {
  2.     public static void main(String[] args) throws IOException {
  3.         /**
  4.          * 需求:把文本文件中的数据读取到集合中,并遍历集合。
  5.          * 要求:文本中每一行数据是一个学生对象的成员变量值
  6.          * 格式:学号,姓名,年龄,居住地
  7.          */
  8.         //1.定义学生类
  9.         //2.创建字符缓冲输入流对象
  10.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  11.         //3.创建ArrayList集合
  12.         ArrayList<Student> list = new ArrayList<>();
  13.         String line;
  14.         //4.调用字符缓冲输入流对象的方法读数据
  15.         while ((line = br.readLine()) != null) {
  16.             //5.把读取到的字符串用split分割,得到一个字符串数组
  17.             String[] s = line.split(",");
  18.             //6.创建学生对象
  19.             Student stu = new Student();
  20.             //7.把字符串数组中的每一个元素取出来,赋值给学生对象的成员变量
  21.             stu.setId(s[0]);
  22.             stu.setName(s[1]);
  23.             stu.setAge(Integer.parseInt(s[2]));
  24.             stu.setAddress(s[3]);
  25.             //8.把学生对象添加到集合
  26.             list.add(stu);
  27.         }
  28.         //9.释放资源
  29.         br.close();
  30.         //10.遍历集合
  31.         for (Student s : list) {
  32.                 //直接输出,因为Student类中重写了toString()
  33.             System.out.println(s);
  34.         }
  35.     }
  36. }
复制代码
运行结果:
  1. Student{id='初二001', name='小明', age=15, address='西安'}
  2. Student{id='初二002', name='小红', age=16, address='北京'}
  3. Student{id='初二003', name='小军', age=17, address='上海'}
  4. Student{id='初二004', name='白展堂', age=14, address='云南'}
  5. Student{id='初二005', name='史珍香', age=13, address='广州'}
复制代码
标准流和打印流

集合到文件数据排序(改进版)
定义学生类:
  1. public class Student {
  2.     private String name;
  3.     private int yuwen;
  4.     private int shuxue;
  5.     private int yingyu;
  6.     public Student() {
  7.     }
  8.     public Student(String name, int yuwen, int shuxue, int yingyu) {
  9.         this.name = name;
  10.         this.yuwen = yuwen;
  11.         this.shuxue = shuxue;
  12.         this.yingyu = yingyu;
  13.     }
  14.        
  15.         //定义获取总分的方法
  16.     public int getSum() {
  17.         return this.yuwen + this.shuxue + this.yingyu;
  18.     }
  19.     public String getName() {
  20.         return name;
  21.     }
  22.     public void setName(String name) {
  23.         this.name = name;
  24.     }
  25.     public int getYuwen() {
  26.         return yuwen;
  27.     }
  28.     public void setYuwen(int yuwen) {
  29.         this.yuwen = yuwen;
  30.     }
  31.     public int getShuxue() {
  32.         return shuxue;
  33.     }
  34.     public void setShuxue(int shuxue) {
  35.         this.shuxue = shuxue;
  36.     }
  37.     public int getYingyu() {
  38.         return yingyu;
  39.     }
  40.     public void setYingyu(int yingyu) {
  41.         this.yingyu = yingyu;
  42.     }
  43.     @Override
  44.     public String toString() {
  45.         return "Student{" +
  46.                 "name='" + name + '\'' +
  47.                 ", yuwen=" + yuwen +
  48.                 ", shuxue=" + shuxue +
  49.                 ", yingyu=" + yingyu +
  50.                 '}';
  51.     }
  52.     @Override
  53.     public boolean equals(Object o) {
  54.         if (this == o) return true;
  55.         if (o == null || getClass() != o.getClass()) return false;
  56.         Student student = (Student) o;
  57.         if (yuwen != student.yuwen) return false;
  58.         if (shuxue != student.shuxue) return false;
  59.         if (yingyu != student.yingyu) return false;
  60.         return name != null ? name.equals(student.name) : student.name == null;
  61.     }
  62.     @Override
  63.     public int hashCode() {
  64.         int result = name != null ? name.hashCode() : 0;
  65.         result = 31 * result + yuwen;
  66.         result = 31 * result + shuxue;
  67.         result = 31 * result + yingyu;
  68.         return result;
  69.     }
  70. }
复制代码
测试类:
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.         /**
  4.          * 需求:键盘录入几个学生信息(姓名,语文成绩,数学成绩,英语成绩)
  5.          * 要求:按照成绩总分由高到低写入文件(排序规则)
  6.          */
  7.         Set<Student> list = new TreeSet<>(new Comparator<Student>() {
  8.             //匿名内部类重写排序方法
  9.             @Override
  10.             public int compare(Student o1, Student o2) {
  11.                 //总分从低到高
  12.                 int num = o2.getSum() - o1.getSum();
  13.                 //如果总分相同,按照语文成绩从高到低
  14.                 int num1 = num == 0 ? o1.getYuwen() - o2.getYuwen() : num;
  15.                 //如果总分相同,语文成绩也相同,按照数学成绩从高到低
  16.                 int num2 = num1 == 0 ? o1.getShuxue() - o2.getShuxue() : num1;
  17.                 //如果总分相同,语文成绩也相同,数学成绩也相同,说明英语成绩肯定相同,那就按照姓名的字母排序
  18.                 int num3 = num2 == 0 ? o1.getName().compareTo(o2.getName()) : num2;
  19.                 return num3;
  20.             }
  21.         });
  22.         for (int i = 0; i < 5; i++) {
  23.             Scanner sc = new Scanner(System.in);
  24.             System.out.println("请输入第" + (i + 1) + "学生信息:");
  25.             System.out.println("姓名:");
  26.             String name = sc.nextLine();
  27.             System.out.println("请输入语文成绩:");
  28.             int yuwen = sc.nextInt();
  29.             System.out.println("请输入数学成绩:");
  30.             int shuxue = sc.nextInt();
  31.             System.out.println("请输入英语成绩:");
  32.             int yingyu = sc.nextInt();
  33.             Student s = new Student(name, yuwen, shuxue, yingyu);
  34.             list.add(s);
  35.         }
  36.         BufferedWriter bw = new BufferedWriter(new FileWriter("idea_test\\java.txt"));
  37.         for (Student stu : list) {
  38.             StringBuilder sb = new StringBuilder();
  39.             sb.append(stu.getName() + "," + stu.getYuwen() + "," + stu.getShuxue() + "," + stu.getYingyu() + ",总分:" + stu.getSum());
  40.             bw.write(sb.toString());
  41.             bw.newLine();
  42.             bw.flush();
  43.         }
  44.         bw.close();
  45.     }
  46. }
复制代码
运行结果:总分从高到低排序
  1. 关羽,89,94,1,总分:184
  2. 孙权,1,99,3,总分:103
  3. 张飞,1,88,9,总分:98
  4. caocao,1,55,9,总分:65
  5. 刘备,1,2,3,总分:6
复制代码
复制单级文件夹
单级文件夹:文件夹中只有文件,没有文件夹
数据源目录
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         /**
  4.          * 需求复制单级文件夹及其内容
  5.          */
  6.         //1.创建数据源目录
  7.         File file = new File("G:\\FileTest\\dog");
  8.         //2.获取创建数据源目录的名称
  9.         String name = file.getName();
  10.         //3.创建目的地File对象
  11.         File file1 = new File("idea_test", name);
  12.         //4.判断目的地是否已经存在该名称的文件夹
  13.         if (!file1.exists()) {
  14.             //5.在目的地创建该名称的文件夹
  15.             file1.mkdir();
  16.         }
  17.         //6.获取数据源文件夹下的所有文件
  18.         File[] files = file.listFiles();
  19.         //7.遍历数组,得到每一个文件对象
  20.         for (File fi : files) {
  21.             //8.获取文件名称
  22.             String fiName = fi.getName();
  23.             //9.在目的地文件夹中,创建fiName同名称的文件
  24.             File fil = new File(file1, fiName);
  25.             //10.复制文件内容:将数据源文件内容复制到目的地文件中
  26.             copyFile(fi, fil);
  27.         }
  28.     }
  29.     /**
  30.      * 字节缓冲流复制文件内容
  31.      * @param f1 数据源文件
  32.      * @param f2 目的地文件
  33.      */
  34.     public static void copyFile(File f1, File f2) throws IOException {
  35.         //缓冲字节输入流对象
  36.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));
  37.         //缓冲字节输出流对象
  38.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));
  39.         //读写文件
  40.         byte[] bytes = new byte[1024];
  41.         int len;
  42.         while ((len = bis.read(bytes)) != -1) {
  43.             bos.write(bytes,0,len);
  44.         }
  45.         bos.close();
  46.         bis.close();
  47.     }
  48. }
复制代码
运行结果:

复制多级文件夹
多级文件夹:文件夹下还有文件夹
数据源文件夹:
  1. public class Demo3 {
  2.     public static void main(String[] args) throws IOException {
  3.         //1.创建数据源目录
  4.         File srcFile = new File("G:\\FileTest");
  5.         //2.创建目的地File对象
  6.         File destFile = new File("D:\");
  7.         //复制文件夹,参数为数据源File对象 和 目的地File对象
  8.         copyFolder(srcFile,destFile);
  9.     }
  10.     /**
  11.      * 复制文件夹
  12.      * @param srcFile    数据源文件夹操作对象
  13.      * @param destFile    目的地文件夹操作对象
  14.      */
  15.     private static void copyFolder(File srcFile,File destFile) throws IOException {
  16.         //判断数据源是否是目录,如果是目录
  17.         if (srcFile.isDirectory()){
  18.             //获取数据源文件夹名称
  19.             String srcFileName = srcFile.getName();
  20.             //目的地文件夹名称
  21.             File destFileName = new File(destFile, srcFileName);
  22.             //判断新文件夹名称在目的地是否存在
  23.             if(!destFileName.exists()){
  24.                 destFileName.mkdir();
  25.             }
  26.             //获取数据源文件夹下的文件
  27.             File[] files = srcFile.listFiles();
  28.             //遍历该数组,得到每一个元素对象
  29.             for (File file : files) {
  30.                 //file可能是文件,也可能是文件夹;所以递归调用复制文件夹方法
  31.                 copyFolder(file,destFileName);
  32.             }
  33.         }else {//如果数据源不是目录
  34.             File newFile = new File(destFile, srcFile.getName());
  35.             copyFile(srcFile,newFile);
  36.         }
  37.     }
  38.     /**
  39.      * 复制文件内容
  40.      * @param f1 数据源文件操作对象
  41.      * @param f2 目的地文件操作对象
  42.      */
  43.     public static void copyFile(File f1, File f2) throws IOException {
  44.         //缓冲字节输入流对象
  45.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));
  46.         //缓冲字节输出流对象
  47.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));
  48.         //读写文件
  49.         byte[] bytes = new byte[1024];
  50.         int len;
  51.         while ((len = bis.read(bytes)) != -1) {
  52.             bos.write(bytes,0,len);
  53.         }
  54.         bos.close();
  55.         bis.close();
  56.     }
  57. }
复制代码
目的地文件夹:

复制文件的异常处理
案例:复制文件;以下是几种处理异常的方法

  • 抛出处理

  • try...catch...finally...处理

  1. /**
  2. * 复制文件内容
  3. *
  4. * @param f1 数据源文件操作对象
  5. * @param f2 目的地文件操作对象
  6. */
  7. public static void copyFile(File f1, File f2) {
  8.     BufferedInputStream bis = null;
  9.     BufferedOutputStream bos = null;
  10.     try {
  11.         //缓冲字节输入流对象
  12.         bis = new BufferedInputStream(new FileInputStream(f1));
  13.         //缓冲字节输出流对象
  14.         bos = new BufferedOutputStream(new FileOutputStream(f2));
  15.         //读写文件
  16.         byte[] bytes = new byte[1024];
  17.         int len;
  18.         while ((len = bis.read(bytes)) != -1) {
  19.             bos.write(bytes, 0, len);
  20.         }
  21.     } catch (IOException e) {
  22.         e.printStackTrace();
  23.     } finally {
  24.         if (bos != null) {
  25.             try {
  26.                 bos.close();
  27.             } catch (IOException e) {
  28.                 e.printStackTrace();
  29.             }
  30.         }
  31.         if (bis != null) {
  32.             try {
  33.                 bis.close();
  34.             } catch (IOException e) {
  35.                 e.printStackTrace();
  36.             }
  37.         }
  38.     }
  39. }
复制代码

  • JDK7的改进方案

  1. /**
  2. * 字节缓冲流复制文件内容
  3. * @param f1 数据源文件
  4. * @param f2 目的地文件
  5. *           JDK7之后的写法,会自动释放资源,不需要close()
  6. */
  7. public static void copyFile1(File f1, File f2) {
  8.     //注意try后面的的小括号
  9.     try(//缓冲字节输入流对象
  10.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));
  11.         //缓冲字节输出流对象
  12.         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2))) {
  13.         //读写文件
  14.         byte[] bytes = new byte[1024];
  15.         int len;
  16.         while ((len = bis.read(bytes)) != -1) {
  17.             bos.write(bytes,0,len);
  18.         }
  19.     } catch (IOException e) {
  20.         e.printStackTrace();
  21.     }
  22. }
复制代码

  • JDK9的改进方案

  1. /**
  2. * 字节缓冲流复制文件内容
  3. * @param f1 数据源文件
  4. * @param f2 目的地文件
  5. */
  6. public static void copyFile2(File f1, File f2) throws FileNotFoundException {
  7.     //缓冲字节输入流对象
  8.     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));
  9.     //缓冲字节输出流对象
  10.     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));
  11.     try(bis;bos) {
  12.         //读写文件
  13.         byte[] bytes = new byte[1024];
  14.         int len;
  15.         while ((len = bis.read(bytes)) != -1) {
  16.             bos.write(bytes,0,len);
  17.         }
  18.     } catch (IOException e) {
  19.         e.printStackTrace();
  20.     }
  21. }
复制代码
标准输入流
System类中有两个静态成员变量

  • public static final InputStream in:“标准”输入流。此流已经 打开并准备提供输入数据。通常此流 对应于键盘输入或由 指定的其他输入源 主机环境或用户。
  • public static final PrintStream out:“标准”输出流。此流已经 打开并准备接受输出数据。通常此流 对应于显示输出或其他输出目标 由主机环境或用户指定。

  • 自己实现输入操作
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  4.         System.out.println("请输入一个字符串:");
  5.         String line = br.readLine();
  6.         System.out.println("你输入的字符串是:" + line);
  7.         System.out.println("请输入一个整数:");
  8.         System.out.println("你输入的整数是:"+Integer.parseInt(br.readLine()));
  9.     }
  10. }
复制代码
运行:
  1. 请输入一个字符串:
  2. hello
  3. 你输入的字符串是:hello
  4. 请输入一个整数:
  5. 123
  6. 你输入的整数是:123
复制代码

  • Java提供的输入类Scanner
  1. //自己实现输入操作太麻烦,所以Java提供了一个类
  2. Scanner sc = new Scanner(System.in);
复制代码
标准输出流
  1. public class Demo1 {
  2.     public static void main(String[] args) {
  3.         PrintStream out = System.out;
  4.         out.print("hello");
  5.         out.println("world");
  6.         out.println(100);
  7.         /**
  8.          * System.out的本质是一个字节输出流
  9.          * print()必须有参数
  10.          * println()可以没有参数
  11.          * PrintStream类有的方法,System.out都可以调用
  12.          */
  13.         System.out.println();
  14.         System.out.print("世界杯");
  15.         System.out.println(123);
  16.     }
  17. }
复制代码
运行:
  1. helloworld
  2. 100
  3. 世界杯123
复制代码
字节打印流
打印流分类:

  • 字节打印流:PrintStream
  • 字符打印流:PrintWriter
打印流的特点:

  • 只负责输出数据,不负责读取数据
  • 有自己的特有方法
字节打印流

  • PrintStream(String fileName):使用指定的文件名创建新的打印流
  • 使用继承父类的方法写数据,查看的时候会转码;使用自己的特有方法写数据,查看的数据原样输出
  1. public class Demo {
  2.     public static void main(String[] args) throws FileNotFoundException {
  3.         //创建字节打印流对象
  4.         PrintStream ps = new PrintStream("idea_test\\java1.txt");
  5.         //写数据
  6.         // 1.字节输出流写数据
  7.         //使用继承父类的方法写数据,查看的时候会转码
  8.         ps.write(97);
  9.         ps.write(98);
  10.         ps.println();
  11.         // 2.字节打印流特有方法写数据
  12.         //使用自己的特有方法写数据,查看的数据原样输出
  13.         ps.println(97);
  14.         ps.print(98);
  15.         ps.close();
  16.     }
  17. }
复制代码
运行结果:

字符打印流
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //创建字符打印流对象
  4.         PrintWriter pw = new PrintWriter("idea_test\\java2.txt");
  5.         pw.write("世界杯");
  6.         pw.write("\r\n");
  7.         pw.flush();
  8.         pw.write("足球");
  9.         pw.write("\r\n");
  10.         pw.flush();
  11.         pw.println("hello");
  12.         pw.flush();
  13.         pw.println("world");
  14.         pw.flush();
  15.         pw.close();
  16.         //PrintWriter(Writer out,boolean outFlush)
  17.         //创建一个新的PrintWriter,true自动刷新flush
  18.         PrintWriter pw1 = new PrintWriter(new FileWriter("idea_test\\java3.txt"), true);
  19.         pw1.println("麻辣");
  20.         pw1.println("米线");
  21.                 pw1.close();
  22.     }
  23. }
复制代码
运行结果:


复制Java文件(打印流改进版)
思路

  • 根据数据源创建字符输入流对象
  • 根据目的地创建字符输出流对象
  • 读写数据,复制文件
  • 释放资源
  1. public class Demo2 {
  2.     public static void main(String[] args) throws IOException {
  3.         /*需求:把idea_test\java.txt复制到idea_test\java4.txt*/
  4.         BufferedReader br = new BufferedReader(new FileReader("idea_test\\java.txt"));
  5.         PrintWriter pw = new PrintWriter(new FileWriter("idea_test\\java4.txt"), true);
  6.         //读写数据
  7.         String line;
  8.         while((line = br.readLine())!=null){
  9.             pw.println(line);
  10.         }
  11.         pw.close();
  12.         br.close();
  13.     }
  14. }
复制代码
对象序列化流

对象序列化流
对象序列化流

  • 就是将对象保存到磁盘中,或者在网络中传输对象
  • 这种机制就是使用一个字节序列表示一个对象,该字节序列包含:对象的类型,对象的数据和对象中存储的属性等
  • 字节序列写到文件之后,相当于文件中持久保存了一个对象的信息
  • 反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化
对象序列化流:ObjectOutputStream
对象反序列化流:ObjectInputStream
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.         /*需求:将学生对象序列化到文件idea_test\hello.txt*/
  4.         //创建对象序列化流操作对象
  5.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("idea_test\\hello.txt"));
  6.         //创建学生对象;Student类实现了Serializable接口
  7.         Student s = new Student("马超", 30);
  8.         //序列化对象
  9.         oos.writeObject(s);
  10.         //释放资源
  11.         oos.close();
  12.     }
  13. }
复制代码
对象反序列化流
  1. public class Demo1 {
  2.     public static void main(String[] args) throws IOException, ClassNotFoundException {
  3.         /*需求:将文件idea_test\hello.txt中的学生对象反序列化*/
  4.         //创建对象反序列化流操作对象
  5.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("idea_test\\hello.txt"));
  6.         //反序列化对象
  7.         Object o = ois.readObject();
  8.         //强转对象类型
  9.         System.out.println((Student)o);
  10.         //释放资源
  11.         ois.close();
  12.     }
  13. }
复制代码
运行结果:
  1. //Student类中重写了toString()
  2. Student{name='马超', age=30}
复制代码
补充问题

Properties类

Properties概述

  • 是一个Map体系的集合类
  • Properties可以保存到流中或从流中加载
  • Properties不能有泛型;默认是类型
Properties作为Map集合
  1. public class PropertiesDemo {
  2.     public static void main(String[] args) {
  3.         //创建集合对象
  4.         Properties p = new Properties();
  5.         //添加元素
  6.         p.put("高一1班", "张铁牛");
  7.         p.put("高一2班", "马牛旦");
  8.         p.put("高一3班", "李桂皮");
  9.         //遍历
  10.         for (Object key : p.keySet()) {
  11.             Object value = p.get(key);
  12.             System.out.println(key + "," + value);
  13.         }
  14.     }
  15. }
复制代码
运行结果:
  1. 高一3班,李桂皮
  2. 高一2班,马牛旦
  3. 高一1班,张铁牛
复制代码
Properties作为集合的特有方法
  1. public class PropertiesDemo {
  2.     public static void main(String[] args) {
  3.         //创建集合对象
  4.         Properties p = new Properties();
  5.         System.out.println("Properties集合:" + p);
  6.         //添加元素
  7.         p.setProperty("高一1班", "张铁牛");
  8.         p.setProperty("高一2班", "马牛旦");
  9.         p.setProperty("高一3班", "李桂皮");
  10.         //返回键的合集
  11.         Set<String> keys = p.stringPropertyNames();
  12.         //遍历
  13.         for (String key : keys) {
  14.             //根据键获取值
  15.             String value = p.getProperty(key);
  16.             System.out.println(key + "," + value);
  17.         }
  18.     }
  19. }
复制代码
运行结果:
  1. Properties集合:{}高一3班,李桂皮
  2. 高一2班,马牛旦
  3. 高一1班,张铁牛
复制代码
Properties和IO流相结合的方法
  1. public class PropertiesDemo1 {
  2.     public static void main(String[] args) throws IOException {
  3.         //把集合中的数据保存到文件
  4.         myStore();
  5.         //把文件中的数据加载到集合
  6.         myLoad();
  7.     }
  8.     /**
  9.      * 把文件中的数据加载到集合
  10.      */
  11.     private static void myLoad() throws IOException {
  12.         //创建集合对象
  13.         Properties p = new Properties();
  14.         //创建字符输入流对象
  15.         FileReader fr = new FileReader("idea_test\\fw.txt");
  16.         //读取元素到集合
  17.         p.load(fr);
  18.         fr.close();
  19.         
  20.         //输出集合
  21.         System.out.println(p);
  22.     }
  23.     /**
  24.      * 把集合中的数据保存到文件
  25.      */
  26.     private static void myStore() throws IOException {
  27.         //创建集合对象
  28.         Properties p = new Properties();
  29.         //添加元素
  30.         p.setProperty("高一1班", "张铁牛");
  31.         p.setProperty("高一2班", "马牛旦");
  32.         p.setProperty("高一3班", "李桂皮");
  33.         //创建字符输出流对象
  34.         FileWriter fw = new FileWriter("idea_test\\fw.txt");
  35.         //将元素写入Properties
  36.         p.store(fw,null);
  37.         fw.close();
  38.     }
  39. }
复制代码
运行结果:
  1. {高一3班=李桂皮, 高一2班=马牛旦, 高一1班=张铁牛}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

傲渊山岳

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表