【自学java笔记#第三十五天#】字符流与文件复制

一、字符流知识点总结

 二、两道经典练习题

1、复制单级文件夹

单级文件夹:该文件夹中不再包含有子文件夹,仅包含各类文件。

package io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
 * 案例:复制单级文件夹(一个目录下没有子目录,只有文件)
 * 需求:把"D:\\itcase"这个文件夹复制到模块目录下
 * 思路:
 * 1、创建数据源目录File对象,路径是D:\\itcase
 * 2、获取数据源目录File对象的名称(itcase)
 * 3、创建目的地目录File对象,路径名是模块名+itcase组成(src\\itcase)
 * 4、判断目的地目录对应的File是否存在,若不存在,就创建
 * 5、获取数据源目录下所有文件的File数组
 * 6、遍历File数组,得到每一个File对象,该File对象,就是数据源文件
 * 7、获取数据源文件File对象的名称
 * 8、创建目的地文件File对象,路径名是目的地目录+mn.jpg组成(src\\itcase\\mn.jpg)
 * 9、复制文件
 * 由于文件不仅仅是文本文件,还有图片,所以采用字节流复制文件
 */

public class IoDemo1 {
    public static void main(String[] args) throws IOException{
        //1、创建数据源目录File对象,路径是D:\\itcase
        File srcFolder=new File("D:\\itcase");//这里的File对象是一个目录
        
        //2、获取数据源目录File对象的名称(itcase)
        String srcFolderName=srcFolder.getName();//保证程序的可维护性
        
        //3、创建目的地目录File对象,路径名是模块名+itcase组成(src\\itcase)
        //File copyFile=new File("src//"+name);//是错误的
        File destFoler=new File("src",srcFolderName);
        
        //4、判断目的地目录对应的File是否存在,若不存在,就创建
        if(!destFoler.exists()) {//若存在,则直接覆盖掉里面的文件
            destFoler.mkdir();
        }
        //5、获取数据源目录下所有文件的File数组
        File[] listFiles=srcFolder.listFiles();//得到的是文件,而不是目录(因为是单级目录)
        
        //6、遍历File数组,得到每一个File对象,该File对象,就是数据源文件
        for(File srcFile:listFiles) {
            
            //7、获取数据源文件File对象的名称
            String srcFileName=srcFile.getName();
            
            //创建目的地文件File对象,路径名是目的地目录+mn.jpg组成(src\\itcase\\mn.jpg)
            //得到的是文件,不是目录
            File destFile=new File(destFoler,srcFileName);
            
            //9、复制文件
            //只能把文件复制到文件中去,不能直接把文件复制给一个文件夹
            copy(srcFile,destFile);
        }
    }

    private static void copy(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、复制多级文件夹

多级文件夹:该文件夹下可能包含有子文件夹,也可能包含有文件;它的子文件夹下还可能有文件夹及文件。

本次程序采用递归的方式,来遍历文件夹。

package io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
 * 案例:复制多级文件夹(一个目录下不仅有子目录,还有文件)
 * 需求:把"D:\\itcase"这个多级文件夹复制到F盘下
 * 思路:
 * 1、创建数据源目录File对象,路径是D:\\itcase
 * 2、创建目的地File对象,路径是C:\\
 * 3、写方法实现文件夹的复制,参数为数据源File对象和目的地File对象
 * 4、判断数据源File是否是目录:
 * 5、是:
 * A:在目的地下创建和数据源File名称相同的目录
 * B:获取数据源File所有文件或者目录的File数组
 * C:遍历该File数组,得到每一个File对象
 * D:把该File对象作为数据源对象,递归调用复制文件夹的方法
 * 不是:说明是文件,由于文件不仅仅是文本文件,还有图片,所以采用字节流复制文件
 */

public class IoDemo1 {
    public static void main(String[] args) throws IOException{
        //1、创建数据源目录File对象,路径是D:\\itcase
        //FileNotFoundException
        File rawFolder=new File("D:\\itcase");//封装源文件路径
        
        //2、创建目的地File对象,路径是C:\\
        File destFolder=new File("C:\\");//封装目的地路径
        
        //3、写方法实现文件夹的复制,参数为数据源File对象和目的地File对象
        //copyFile(rawFolder,destFolder);
        copyFolder(rawFolder,destFolder);//调用复制文件夹的方法
    }

    private static void copyFolder(File rawFolder, File destFolder) throws IOException {
        // 4、判断数据源File是否是目录:
        if(rawFolder.isDirectory()) {//如果源文件是目录
            //A:在目的地下创建和数据源File名称相同的目录
            String rawFolderName=rawFolder.getName();//先创建一个"E:\\itcase"
            File newFolder=new File(destFolder,rawFolderName);//只是封装了路径,没有创建目录
            if(!newFolder.exists()) {
                newFolder.mkdir();
            }
            //B:获取数据源File所有文件或者目录的File数组
            File[] arrFile=rawFolder.listFiles();//得到源文件路径中的所有File对象
            //C:遍历该File数组,得到每一个File对象
            for(File file:arrFile) {
                //D:把该File对象作为数据源对象,递归调用复制文件夹的方法
                copyFolder(file,newFolder);//无论这些File对象是不是文件夹,都调用复制文件夹的方法
            }
        }
        else {
            File newFile=new File(destFolder,rawFolder.getName());
            copyFile(rawFolder,newFile);
        }
        
    }

    //字节缓冲流复制文件
    private static void copyFile(File rawFolder, File newFile) throws IOException {
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(newFile));
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(rawFolder));
        byte[] bys=new byte[1024];
        int len;
        while((len=bis.read())!=-1) {
            bos.write(bys,0,len);
        }
        bos.close();
        bis.close();
    }
        
}

三、结合具体的类,来使用字符流

学生类:

package io;

public class Student implements Comparable<Student>{
//public class Student {    
    private String name;
    private int mathScore;
    private int chineseScore;
    private int englishScore;
    
    public Student() {
        super();
    }

    public Student(String name, int mathScore, int chineseScore,int englishScore) {
        super();
        this.name = name;
        this.mathScore = mathScore;
        this.chineseScore = chineseScore;
        this.englishScore=englishScore;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return the mathScore
     */
    public int getMathScore() {
        return mathScore;
    }

    /**
     * @return the chineseScore
     */
    public int getChineseScore() {
        return chineseScore;
    }
    
    public int getenglishScore() {
        return englishScore;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @param mathScore the mathScore to set
     */
    public void setMathScore(int mathScore) {
        this.mathScore = mathScore;
    }

    /**
     * @param chineseScore the chineseScore to set
     */
    public void setChineseScore(int chineseScore) {
        this.chineseScore = chineseScore;
    }
    
    public void setenglishScore(int englishScore) {
        this.englishScore = englishScore;
    }
    
    public int getSumScore() {
        return this.chineseScore+this.mathScore+this.englishScore;
    }

    @Override
    public String toString() {
        return name+","+mathScore+","+chineseScore+","+englishScore+","+this.getSumScore();
    }
    
    public int compareTo(Student other) {
        //int diff=(Integer.compare(this.getSumScore(), other.getSumScore()))*(-1);
        int diff=other.getSumScore()-this.getSumScore();
        int diff1=diff==0?this.getChineseScore()-other.getChineseScore():diff;
        int diff2=diff1==0?this.getMathScore()-other.getMathScore():diff1;
        int diff3=diff2==0?this.getName().compareTo(other.getName()):diff2;
        return diff3;
    }
}

主类:

package io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/*
 * 案例:集合到文件(数据排序改进版)
 * 需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)
 * 要求按照成绩总分从高到低写入文本文件
 * 格式:姓名,语文成绩,数学成绩,英语成绩
 * 举例:林青霞,98,99,100
 */
import java.util.Scanner;
import java.util.*;

public class IoDemo1 {
    public static void main(String[] args) throws IOException{
        //通过比较器排序进行排序
        TreeSet<Student>trs=new TreeSet<Student>();
//        TreeSet<Student>trs=new TreeSet<Student>(new Comparator<Student>() {
//
//            @Override
//            public int compare(Student s1, Student s2) {
//                //主要条件
//                int num=s2.getSumScore()-s1.getSumScore();
//                //次要条件
//                int num1=num==0?s1.getChineseScore()-s2.getChineseScore():num;
//                int num2=num1==0?s1.getMathScore()-s2.getMathScore():num1;
//                int num3=num2==0?s1.getName().compareTo(s2.getName()):num2;
//                return num3;
//            }
//            
//        });
        Scanner in=new Scanner(System.in);
        for(int i=1;i<6;i++) {
            System.out.println("请输入第"+i+"个学生的成绩:(格式为:林青霞,98,99,100)");
            String line=in.nextLine();
            String[] str=line.split(",");
            Student s=new Student();
            s.setName(str[0]);
            s.setChineseScore(Integer.parseInt(str[1]));
            s.setMathScore(Integer.parseInt(str[2]));
            s.setenglishScore(Integer.parseInt(str[3]));
            trs.add(s);
        }
        in.close();
        
        BufferedWriter bfw=new BufferedWriter(new FileWriter("D:\\troye.txt"));
        String s;
        for(Student stu:trs) {
            s=stu.toString();
            bfw.write(s);
            bfw.newLine();
            bfw.flush();
        }
        bfw.close();
    }
}

四、总结

今天可能是学java以来效率最高的一天,各种知识点掌握得也很快。别看每一次的练习都不难,但是还是很容易出现岔子。以前在集合排序这一块还是会纠结老半天,想不出来。今天学着学着突然顿悟了,发现不过就是那么回事。所以如果当下没有解决的技术问题,先放在一边,慢慢地在后续的学习中会找到答案的!

猜你喜欢

转载自www.cnblogs.com/yizhinailu/p/12722769.html