Day14——File案例——IO流之多级复制文件

1.文件复制:

  • 需求:复制多级文件

    • 数据源:H:\java_ex;
    • 目的地:C:\Users\Administrator\Desktop ;
  • 分析:

    • 1.对数据源进行封装:

      File srcFile = new File("H:\\java_ex");
      
    • 2.对目的地进行封装:

      File targetFile = new File("C:\\Users\\Administrator\\Desktop");
      
    • 3.判断File是文件还是文件夹

      srcFile.isDirectory()
      
      • 是文件夹
        • 在目的地下创建该文件夹
          File tarFolder = new File(targetFile, srcFile.getName());
          tarFolder.mkdirs();
          
        • 获取该文件的所有文件或者对象
           File[] files = srcFile.listFiles();
          
        • 用增强for循环遍历files对象得到每一个File对象
        • 回到3,采用递归直到遍历出所有文件为止;
      • 是文件:
        • 复制文件
  • 代码实现:

import java.io.*;

public class CopyFolder01 {
    public static void main(String[] args) throws IOException {
        //封装原文件
        File srcFile = new File("H:\\java_ex");
        //封装目标文件夹
        File targetFile = new File("C:\\Users\\Administrator\\Desktop");
        //调用方法:
        CopyFolder(srcFile, targetFile);
    }

    private static boolean CopyFolder(File srcFile, File targetFile) throws IOException {
        //递归出口
        if (!srcFile.exists()) {
            return false;
        }
        //判断是否为文件夹
        if (srcFile.isDirectory()) {
            //是,创建文件夹用来存放复制的文件
            File tarFolder = new File(targetFile, srcFile.getName());
            tarFolder.mkdirs();
            File[] files = srcFile.listFiles();
            for (File file : files) {
                CopyFolder(file, tarFolder);
            }
        } else {
            //否,则为文件,调用复制文件方法
            File tarFile = new File(targetFile, srcFile.getName());
            CopyFiles(srcFile, tarFile);
        }
        return true;
    }

    private static void CopyFiles(File srcFolder, File tarFile) throws IOException {
        //封装原文件
        FileInputStream fis = new FileInputStream(srcFolder);
        //封装目标文件
        FileOutputStream fos = new FileOutputStream(tarFile);

        byte[] bys = new byte[1024];
        int len;
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }
		//释放资源
        fos.close();
        fis.close();
    }
}

  • 问题:
    在过程中,如果遇到以下问题:
Exception in thread "main" java.io.FileNotFoundException: C:\Users\Administrator\Desktop\java_ex\15.txt\15.txt (系统找不到指定的路径。)

问题出现在文件复制模块:

在这里插入图片描述
在复制模块的时候,tarFile已经是文件名,而不是文件夹,不能采用以下构造方法创建文件实例:

 File(File parent, String child),从父抽象路径名和子路径名字符串创建新的File实例;

2.录入信息,并保存为txt文件

  • 需求:
    键盘录入3个学生信息(姓名,语文成绩(chineseScore),数学成绩(mathScore),英语成绩(englishScore)),并存为txt格式;
  • 分析:
    • 创建一个学生类,包含所要录入的信息(姓名,成绩):

          private String name;
          int ChineseScore; 
          int MathScore; 
          int EnglishScore;
      
    • 采用TreeSet集合存储学生对象,便于排序;

    • 从键盘录入学生信息,每次将所录入的信息封装为一个学生对象,并添加到集合中;

    • 创建一个高效字符流输出对象,用来将学生信息写入指定的文本文件中;

    • 释放资源;

  • 代码实现:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.Scanner;
import java.util.TreeSet;

public class InputInformation {
    public static void main(String[] args) throws IOException {
        //因为需要排序,所以采用TreeSet集合来进行存储学生对象
        TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //总分比较
                int num = s2.sumScore() - s1.sumScore();
                //语文成绩比较
                int num2 = (num == 0) ? s2.getChineseScore() - s1.getChineseScore() : num;
                //数学成绩比较
                int num3 = (num == 0) ? s2.getMathScore() - s1.getMathScore() : num2;
                //英语成绩比较
                int num4 = (num == 0) ? s2.getEnglishScore() - s1.getEnglishScore() : num3;
                //姓名比较
                int num5 = (num == 0) ? s2.getName().compareTo(s1.getName()) : num4;

                return num5;
            }
        });

        //录入学生信息
        for (int i = 1; i <= 3; i++) {
            System.out.println("---------------第" + i + "个学生的信息开始录入---------------");

            Scanner scanner = new Scanner(System.in);
            System.out.print("第" + i + "个学生的姓名:");
            String name = scanner.nextLine();
            System.out.print("第" + i + "个学生的语文成绩:");
            String chinese = scanner.nextLine();
            System.out.print("第" + i + "个学生的数学成绩:");
            String math = scanner.nextLine();
            System.out.print("第" + i + "个学生的英语成绩:");
            String english = scanner.nextLine();

            Student student = new Student();
            student.setName(name);
            student.setChineseScore(Integer.parseInt(chinese));
            student.setMathScore(Integer.parseInt(math));
            student.setEnglishScore(Integer.parseInt(english));

            students.add(student);
        }

        //创建一个字符流输出对象,用来写入数据
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String str = format.format(date);

        BufferedWriter bw = new BufferedWriter(new FileWriter(str + "学生成绩.txt"));
        bw.write("姓名\t语文成绩\t英语成绩\t数学成绩\t总分");
        bw.newLine();
        bw.flush();

        //遍历
        for (Student student : students) {
            bw.write(student.getName()+"\t\t"+student.getChineseScore()+"\t\t\t\t"+student.getMathScore()+"\t\t\t\t"+student.getEnglishScore()+"\t\t\t"+student.sumScore());
            bw.newLine();
            bw.flush();
        }

        //释放资源
        bw.close();
    }
}
  • 录入成绩:
    在这里插入图片描述
  • 查看录入结果:
    在这里插入图片描述
  • 以上代码缺憾:
  1. 没有学生输入信息的判断;若学生输入信息不规范,应提示重新输入,直到规范输入为止,此处可以采用正则表达式来进行匹配;
  2. 处理异常不够规范,没有采用捕获异常,直接抛出,这种甩锅行为,有点不负责;
    以上问题,等忙完这段时间,在进行修改;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值