Java(36)IO流案例与总结

作者:季沐测试笔记
原文地址https://www.cnblogs.com/testero/p/15228455.html
博客主页https://www.cnblogs.com/testero

1 IO流小结

  • 字节流

  • 字符流

2 练习案例

2.1 集合到文件

  • 案例需求

    把文本文件中的数据读取到集合中,并遍历集合。要求:文件中每一行数据是一个集合元素

  • 实现步骤

    • 创建字符缓冲输入流对象
    • 创建ArrayList集合对象
    • 调用字符缓冲输入流对象的方法读数据
    • 把读取到的字符串数据存储到集合中
    • 释放资源
    • 遍历集合
  • 代码实现

    public class TxtToArrayListDemo {
        public static void main(String[] args) throws IOException {
            //创建字符缓冲输入流对象
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\array.txt"));
    
            //创建ArrayList集合对象
            ArrayList<String> array = new ArrayList<String>();
    
            //调用字符缓冲输入流对象的方法读数据
            String line;
            while ((line=br.readLine())!=null) {
                //把读取到的字符串数据存储到集合中
                array.add(line);
            }
            //释放资源
            br.close();
            //遍历集合
            for(String s : array) {
                System.out.println(s);
            }
        }
    }
    

2.2 文件到集合

  • 案例需求

    把ArrayList集合中的字符串数据写入到文本文件。要求:每一个字符串元素作为文件中的一行数据

  • 实现步骤

    • 创建ArrayList集合
    • 往集合中存储字符串元素
    • 创建字符缓冲输出流对象
    • 遍历集合,得到每一个字符串数据
    • 调用字符缓冲输出流对象的方法写数据
    • 释放资源
  • 代码实现

    public class ArrayListToTxtDemo {
        public static void main(String[] args) throws IOException {
            //创建ArrayList集合
            ArrayList<String> array = new ArrayList<String>();
    
            //往集合中存储字符串元素
            array.add("hello");
            array.add("world");
            array.add("java");
    
            //创建字符缓冲输出流对象
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\array.txt"));
    
            //遍历集合,得到每一个字符串数据
            for(String s : array) {
                //调用字符缓冲输出流对象的方法写数据
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
    
            //释放资源
            bw.close();
        }
    }
    

2.3 点名器

  • 案例需求

    我有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随点名器

  • 实现步骤

    • 创建字符缓冲输入流对象
    • 创建ArrayList集合对象
    • 调用字符缓冲输入流对象的方法读数据
    • 把读取到的字符串数据存储到集合中
    • 释放资源
    • 使用Random产生一个随机数,随机数的范围在:[0,集合的长度)
    • 把第6步产生的随机数作为索引到ArrayList集合中获取值
    • 把第7步得到的数据输出在控制台
  • 代码实现

    public class CallNameDemo {
        public static void main(String[] args) throws IOException {
            //创建字符缓冲输入流对象
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\names.txt"));
    
            //创建ArrayList集合对象
            ArrayList<String> array = new ArrayList<String>();
    
            //调用字符缓冲输入流对象的方法读数据
            String line;
            while ((line=br.readLine())!=null) {
                //把读取到的字符串数据存储到集合中
                array.add(line);
            }
    
            //释放资源
            br.close();
    
            //使用Random产生一个随机数,随机数的范围在:[0,集合的长度)
            Random r = new Random();
            int index = r.nextInt(array.size());
    
            //把第6步产生的随机数作为索引到ArrayList集合中获取值
            String name = array.get(index);
    
            //把第7步得到的数据输出在控制台
            System.out.println("幸运者是:" + name);
        }
    }
    

2.4 集合到文件改进版

  • 案例需求

    把ArrayList集合中的学生数据写入到文本文件。要求:每一个学生对象的数据作为文件中的一行数据
    ​ 格式:学号,姓名,年龄,居住地 举例:test001,林青霞,30,西安

  • 实现步骤

    • 定义学生类
    • 创建ArrayList集合
    • 创建学生对象
    • 把学生对象添加到集合中
    • 创建字符缓冲输出流对象
    • 遍历集合,得到每一个学生对象
    • 把学生对象的数据拼接成指定格式的字符串
    • 调用字符缓冲输出流对象的方法写数据
    • 释放资源
  • 代码实现

    • 学生类

      public class Student {
          private String sid;
          private String name;
          private int age;
          private String address;
      
          public Student() {
          }
      
          public Student(String sid, String name, int age, String address) {
              this.sid = sid;
              this.name = name;
              this.age = age;
              this.address = address;
          }
      
          public String getSid() {
              return sid;
          }
      
          public void setSid(String sid) {
              this.sid = sid;
          }
      
          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 getAddress() {
              return address;
          }
      
          public void setAddress(String address) {
              this.address = address;
          }
      }
      
    • 测试类

      public class ArrayListToFileDemo {
          public static void main(String[] args) throws IOException {
              //创建ArrayList集合
              ArrayList<Student> array = new ArrayList<Student>();
      
              //创建学生对象
              Student s1 = new Student("test001", "林青霞", 30, "西安");
              Student s2 = new Student("test002", "张曼玉", 35, "武汉");
              Student s3 = new Student("test003", "王祖贤", 33, "郑州");
      
              //把学生对象添加到集合中
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //创建字符缓冲输出流对象
              BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\students.txt"));
      
              //遍历集合,得到每一个学生对象
              for (Student s : array) {
                  //把学生对象的数据拼接成指定格式的字符串
                  StringBuilder sb = new StringBuilder();
                  sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
      
                  //调用字符缓冲输出流对象的方法写数据
                  bw.write(sb.toString());
                  bw.newLine();
                  bw.flush();
              }
      
              //释放资源
              bw.close();
          }
      }
      

2.5 文件到集合改进版

  • 案例需求

    把文本文件中的数据读取到集合中,并遍历集合。要求:文件中每一行数据是一个学生对象的成员变量值
    举例:test001,林青霞,30,西安

  • 实现步骤

    • 定义学生类
    • 创建字符缓冲输入流对象
    • 创建ArrayList集合对象
    • 调用字符缓冲输入流对象的方法读数据
    • 把读取到的字符串数据用split()进行分割,得到一个字符串数组
    • 创建学生对象
    • 把字符串数组中的每一个元素取出来对应的赋值给学生对象的成员变量值
    • 把学生对象添加到集合
    • 释放资源
    • 遍历集合
  • 代码实现

    • 学生类

      ​ 同上

    • 测试类

      public class FileToArrayListDemo {
          public static void main(String[] args) throws IOException {
              //创建字符缓冲输入流对象
              BufferedReader br = new BufferedReader(new FileReader("myCharStream\\students.txt"));
      
              //创建ArrayList集合对象
              ArrayList<Student> array = new ArrayList<Student>();
      
              //调用字符缓冲输入流对象的方法读数据
              String line;
              while ((line = br.readLine()) != null) {
                  //把读取到的字符串数据用split()进行分割,得到一个字符串数组
                  String[] strArray = line.split(",");
      
                  //创建学生对象
                  Student s = new Student();
                  //把字符串数组中的每一个元素取出来对应的赋值给学生对象的成员变量值
                  //test001,林青霞,30,西安
                  s.setSid(strArray[0]);
                  s.setName(strArray[1]);
                  s.setAge(Integer.parseInt(strArray[2]));
                  s.setAddress(strArray[3]);
      
                  //把学生对象添加到集合
                  array.add(s);
              }
      
              //释放资源
              br.close();
      
              //遍历集合
              for (Student s : array) {
                  System.out.println(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
              }
          }
      }
      

2.6集合到文件数据排序改进版

2.6.1案例需求

  • 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)。要求按照成绩总分从高到低写入文本文件
  • 格式:姓名,语文成绩,数学成绩,英语成绩 举例:林青霞,98,99,100

2.6.2分析步骤

  1. 定义学生类
  2. 创建TreeSet集合,通过比较器排序进行排序
  3. 键盘录入学生数据
  4. 创建学生对象,把键盘录入的数据对应赋值给学生对象的成员变量
  5. 把学生对象添加到TreeSet集合
  6. 创建字符缓冲输出流对象
  7. 遍历集合,得到每一个学生对象
  8. 把学生对象的数据拼接成指定格式的字符串
  9. 调用字符缓冲输出流对象的方法写数据
  10. 释放资源

2.6.3代码实现

  • 学生类

    public class Student {
        // 姓名
        private String name;
        // 语文成绩
        private int chinese;
        // 数学成绩
        private int math;
        // 英语成绩
        private int english;
    
        public Student() {
            super();
        }
    
        public Student(String name, int chinese, int math, int english) {
            super();
            this.name = name;
            this.chinese = chinese;
            this.math = math;
            this.english = english;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getChinese() {
            return chinese;
        }
    
        public void setChinese(int chinese) {
            this.chinese = chinese;
        }
    
        public int getMath() {
            return math;
        }
    
        public void setMath(int math) {
            this.math = math;
        }
    
        public int getEnglish() {
            return english;
        }
    
        public void setEnglish(int english) {
            this.english = english;
        }
    
        public int getSum() {
            return this.chinese + this.math + this.english;
        }
    }
    
  • 测试类

    public class TreeSetToFileDemo {
        public static void main(String[] args) throws IOException {
            //创建TreeSet集合,通过比较器排序进行排序
            TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
                @Override
                public int compare(Student s1, Student s2) {
                    //成绩总分从高到低
                    int num = s2.getSum() - s1.getSum();
                    //次要条件
                    int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                    int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
                    int num4 = num3 == 0 ? s1.getName().compareTo(s2.getName()) : num3;
                    return num4;
                }
            });
    
            //键盘录入学生数据
            for (int i = 0; i < 5; i++) {
                Scanner sc = new Scanner(System.in);
                System.out.println("请录入第" + (i + 1) + "个学生信息:");
                System.out.println("姓名:");
                String name = sc.nextLine();
                System.out.println("语文成绩:");
                int chinese = sc.nextInt();
                System.out.println("数学成绩:");
                int math = sc.nextInt();
                System.out.println("英语成绩:");
                int english = sc.nextInt();
    
                //创建学生对象,把键盘录入的数据对应赋值给学生对象的成员变量
                Student s = new Student();
                s.setName(name);
                s.setChinese(chinese);
                s.setMath(math);
                s.setEnglish(english);
    
                //把学生对象添加到TreeSet集合
                ts.add(s);
            }
    
            //创建字符缓冲输出流对象
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\ts.txt"));
    
            //遍历集合,得到每一个学生对象
            for (Student s : ts) {
                //把学生对象的数据拼接成指定格式的字符串
                //格式:姓名,语文成绩,数学成绩,英语成绩
                StringBuilder sb = new StringBuilder();
                sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish()).append(",").append(s.getSum());
    
    //            调用字符缓冲输出流对象的方法写数据
                bw.write(sb.toString());
                bw.newLine();
                bw.flush();
            }
    
            //释放资源
            bw.close();
        }
    }
    

2.7复制单级文件夹

2.7.1案例需求

  • 把“E:\itcast”这个文件夹复制到模块目录下

2.7.2分析步骤

  1. 创建数据源目录File对象,路径是E:\itcast

  2. 获取数据源目录File对象的名称

  3. 创建目的地目录File对象,路径由(模块名+第2步获取的名称)组成

  4. 判断第3步创建的File是否存在,如果不存在,就创建

  5. 获取数据源目录下所有文件的File数组

  6. 遍历File数组,得到每一个File对象,该File对象,其实就是数据源文件

  7. 获取数据源文件File对象的名称

  8. 创建目的地文件File对象,路径由(目的地目录+第7步获取的名称)组成

  9. 复制文件

    ​ 由于不清楚数据源目录下的文件都是什么类型的,所以采用字节流复制文件

    ​ 采用参数为File的构造方法

2.7.3代码实现

public class CopyFolderDemo {
    public static void main(String[] args) throws IOException {
        //创建数据源目录File对象,路径是E:\\itcast
        File srcFolder = new File("E:\\itcast");

        //获取数据源目录File对象的名称(itcast)
        String srcFolderName = srcFolder.getName();

        //创建目的地目录File对象,路径名是模块名+itcast组成(myCharStream\\itcast)
        File destFolder = new File("myCharStream",srcFolderName);

        //判断目的地目录对应的File是否存在,如果不存在,就创建
        if(!destFolder.exists()) {
            destFolder.mkdir();
        }

        //获取数据源目录下所有文件的File数组
        File[] listFiles = srcFolder.listFiles();

        //遍历File数组,得到每一个File对象,该File对象,其实就是数据源文件
        for(File srcFile : listFiles) {
            //数据源文件:E:\\itcast\\mn.jpg
            //获取数据源文件File对象的名称(mn.jpg)
            String srcFileName = srcFile.getName();
            //创建目的地文件File对象,路径名是目的地目录+mn.jpg组成(myCharStream\\itcast\\mn.jpg)
            File destFile = new File(destFolder,srcFileName);
            //复制文件
            copyFile(srcFile,destFile);
        }
    }

    private static void copyFile(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));

        byte[] bys = new byte[1024];
        int len;
        while ((len=bis.read(bys))!=-1) {
            bos.write(bys,0,len);
        }

        bos.close();
        bis.close();
    }
}

2.8复制多级文件夹

2.8.1案例需求

  • 把“E:\itcast”这个文件夹复制到 F盘目录下

2.8.2分析步骤

  1. 创建数据源File对象,路径是E:\itcast

  2. 创建目的地File对象,路径是F:\

  3. 写方法实现文件夹的复制,参数为数据源File对象和目的地File对象

  4. 判断数据源File是否是文件

    ​ 是文件:直接复制,用字节流

    ​ 不是文件:

    ​ 在目的地下创建该目录

    ​ 遍历获取该目录下的所有文件的File数组,得到每一个File对象

    ​ 回到3继续(递归)

2.8.3代码实现

public class CopyFoldersDemo {
    public static void main(String[] args) throws IOException {
        //创建数据源File对象,路径是E:\\itcast
        File srcFile = new File("E:\\itcast");
        //创建目的地File对象,路径是F:\\
        File destFile = new File("F:\\");

        //写方法实现文件夹的复制,参数为数据源File对象和目的地File对象
        copyFolder(srcFile,destFile);
    }

    //复制文件夹
    private static void copyFolder(File srcFile, File destFile) throws IOException {
        //判断数据源File是否是目录
        if(srcFile.isDirectory()) {
            //在目的地下创建和数据源File名称一样的目录
            String srcFileName = srcFile.getName();
            File newFolder = new File(destFile,srcFileName); //F:\\itcast
            if(!newFolder.exists()) {
                newFolder.mkdir();
            }

            //获取数据源File下所有文件或者目录的File数组
            File[] fileArray = srcFile.listFiles();

            //遍历该File数组,得到每一个File对象
            for(File file : fileArray) {
                //把该File作为数据源File对象,递归调用复制文件夹的方法
                copyFolder(file,newFolder);
            }
        } else {
            //说明是文件,直接复制,用字节流
            File newFile = new File(destFile,srcFile.getName());
            copyFile(srcFile,newFile);
        }
    }

    //字节缓冲流复制文件
    private static void copyFile(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));

        byte[] bys = new byte[1024];
        int len;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }

        bos.close();
        bis.close();
    }
}

3 .复制文件的异常处理做法

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

    }

    //try...catch...finally
    private static void method2() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("fr.txt");
            fw = new FileWriter("fw.txt");

            char[] chs = new char[1024];
            int len;
            while ((len = fr.read()) != -1) {
                fw.write(chs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fw!=null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fr!=null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //抛出处理
    private static void method1() throws IOException {
        FileReader fr = new FileReader("fr.txt");
        FileWriter fw = new FileWriter("fw.txt");

        char[] chs = new char[1024];
        int len;
        while ((len = fr.read()) != -1) {
            fw.write(chs, 0, len);
        }

        fw.close();
        fr.close();
    }
}
posted @ 2021-08-10 23:20  季沐测试笔记  阅读(119)  评论(0编辑  收藏  举报