day19Java-IO-IO结合集合练习

博客名称
Java-(中级)

复制文件

将c:\a.txt复制到d:\b.txt
使用字符流的五中方式复制文本文件

分析:
	复制数据,如果我们知道用记事本打开并能够读懂,就用字符流,否则用字节流。
	通过该原理,我们知道我们应该采用字符流更方便一些。
	而字符流有5种方式,所以做这个题目我们有5种方式。推荐掌握第5种。
数据源:
  	d:\\a.txt -- FileReader -- BufferdReader
目的地:
  	e:\\b.txt -- FileWriter -- BufferedWriter

代码演示

public class CopyFileDemo {
    public static void main(String[] args) {
        String srcFolder = "d:\\a.txt";
        String tarFolder = "e:\\b.txt";

        //字符缓冲流一次读取一行
        zfhclReaderLine(srcFolder, "e:\\b.txt");
        //字符缓冲流一次读取一个字符数组
        zfhclReaderCharArray(srcFolder, "e:\\c.txt");
        //字符缓冲流一次读取一个字符
        zfhclReaderChar(srcFolder, "e:\\d.txt");
        //字符流一次读取一个字符数组
        zflreaderCharArray(srcFolder, "e:\\e.txt");
        //字符流一次读取一个字符
        zflreadderOneChar(srcFolder, "e:\\f.txt");

    }

    //字符缓冲流一次读取一行
    public static void zfhclReaderLine(String srcFolder, String tarFolder) {
        //封装数据源
        BufferedReader br = null;
        //封装目的地
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(srcFolder));
            bw = new BufferedWriter(new FileWriter(tarFolder));
            //一次读取一行
            String line = null;
            while ((line = br.readLine()) != null) {
                //读取一行数据
                bw.write(line);
                //换行
                bw.newLine();
                //刷新缓冲区
                bw.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字符缓冲流一次读取一个字符数组
    public static void zfhclReaderCharArray(String srcFolder, String tarFolder) {
        //封装数据源
        BufferedReader br = null;
        //封装目的地
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(srcFolder));
            bw = new BufferedWriter(new FileWriter(tarFolder));

            //字符缓冲流一次读取一个字符数组
            char[] chars = new char[1024];
            int len = 0;
            while ((len = br.read(chars)) != -1) {
                bw.write(chars, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字符缓冲流一次读取一个字符
    public static void zfhclReaderChar(String srcFolder, String tarFolder) {
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            br = new BufferedReader(new FileReader(srcFolder));
            bw = new BufferedWriter(new FileWriter(tarFolder));

            //字符缓冲流一次读取一个字符
            int ch = 0;
            while ((ch = br.read()) != -1) {
                bw.write(ch);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字符流一次读取一个字符数组
    public static void zflreaderCharArray(String srcFolder, String tarFolder) {
        //封装数据源
        FileReader fr = null;
        //封装目的地
        FileWriter fw = null;
        try {
            fr = new FileReader(srcFolder);
            fw = new FileWriter(tarFolder);
            //一次读取一个字符数组
            char[] chars = new char[1024];
            int len = 0;
            while ((len = fr.read(chars)) != -1) {
                fw.write(chars, 0, len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字符流一次读取一个字符
    public static void zflreadderOneChar(String srcFolder, String tarFolder) {
        //封装数据源
        FileReader fr = null;
        //封装目的地
        FileWriter fw = null;
        try {
            fr = new FileReader(srcFolder);
            fw = new FileWriter(tarFolder);
            //一次读取一个字符
            int by = 0;
            while ((by = fr.read()) != -1) {
                fw.write(by);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:e:\b.txt,e:\c.txt,e:\d.txt,e:\e.txt,e:\f.txt文件中的中结果

且随疾风前行,身后一亦需留心。
我于杀戮之中绽放,亦如黎明中的花朵。
复制图片

将c:\歼20战斗机.jpg复制到d:\歼20战斗机.jpg
使用四种方式复制图片

分析:
	复制数据,如果我们知道用记事本打开并能够读懂,就用字符流,否则用字节流。
	通过该原理,我们知道我们应该采用字节流。
	而字节流有4种方式,所以做这个题目我们有4种方式。推荐掌握第4种。
数据源:
	d:\歼20战斗机.jpg -- FileInputStream -- BufferedInputStream
目的地:
	e:\歼20战斗机.jpg -- FileOuputStream -- BufferedOutputStream

代码演示:

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

        String srcFolder = "D:\\歼20战斗机.jpg";
        //String tarFolder = "E:\\歼20战斗机.jpg";
        //字节缓冲流一次读取一个字节数组
        zjhclReaderByteArray(srcFolder, "E:\\歼20战斗机1.jpg");
        //字节缓冲流一次读取一个字节
        zjhclReaderOneByte(srcFolder, "E:\\歼20战斗机2.jpg");
        //字节流一次读取一个字节数组
        zjlReaderByteArray(srcFolder, "E:\\歼20战斗机3.jpg");
        //字节流一次读取一个字节
        zjlReaderOneByte(srcFolder, "E:\\歼20战斗机4.jpg");
    }

    //字节缓冲流一次读取一个字节数组
    public static void zjhclReaderByteArray(String srcFolder, String tarFolder) {
        //封装数据源
        BufferedInputStream bis = null;
        //封装目的地
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFolder));
            bos = new BufferedOutputStream(new FileOutputStream(tarFolder));
            //一次读取字节数组
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bis.read(bytes)) != -1) {
                //写数据
                bos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字节缓冲流一次读取一个字节
    public static void zjhclReaderOneByte(String srcFolder, String tarFolder) {
        //封装数据源
        BufferedInputStream bis = null;
        //封装目的地
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFolder));
            bos = new BufferedOutputStream(new FileOutputStream(tarFolder));
            //字节缓冲流一次读取一个字节
            int by = 0;
            while ((by = bis.read()) != -1) {
                bos.write(by);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字节流一次读取一个字节数组
    public static void zjlReaderByteArray(String srcFolder, String tarFolder) {
        //封装数据源
        FileInputStream fis = null;
        //封装目的地
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(srcFolder);
            fos = new FileOutputStream(tarFolder);
            //字节流一次读取一个字节数组
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字节流一次读取一个字节
    public static void zjlReaderOneByte(String srcFolder, String tarFolder) {
        //封装数据源
        FileInputStream fis = null;
        //封装目的地
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(srcFolder);
            fos = new FileOutputStream(tarFolder);
            //字节流一次读取一个字节
            int by = 0;
            while ((by = fis.read()) != -1) {
                fos.write(by);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:e:\歼20战斗机12345.jpg
在这里插入图片描述

把集合的数据存储到文件

分析:把集合中的数据,存储到文本文件中,通过存储值可以看出来使用的字符缓冲输出流。

数据源:
      ArrayList
目的地:
      a.txt -- FileWriter -- BufferedWriter

代码演示

public class ArrayListToTextDemo {
    public static void main(String[] args) throws IOException {
        //创建集合
        ArrayList<String> list = new ArrayList<String>();
        //创建字符缓冲输出流
        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

        //添加集合
        list.add("hello");
        list.add("world");
        list.add("java");

        for(String s:list){
            bw.write(s);
            //刷新缓冲区
            bw.flush();
            //换行
            bw.newLine();
        }
        //关闭流
        bw.close();
    }
}

结果:a.txt文件的内容

hello
world
java

把文件的数据存储到集合

分析:把文件中的数据存储到集合中,通过查看文件中的值,使用字符缓冲输入流

数据源:
     a.txt  -- FileReader -- BufferedReader
目的地:
      ArrayList

代码演示

public class TextToArrayListDemo {
    public static void main(String[] args) throws IOException {

        //创建数据源
         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
       //创建目的地
        ArrayList<String> list = new ArrayList<String>();
        //一次读取字符数组
        /*char[] chars = new char[1024];
        int len = 0;
        while ((len= br.read(chars))!=-1){
            list.add(new String(chars,0,len));
        }*/

        //一次读取一行
        String ss = null;
        while ((ss=br.readLine())!=null){
           // System.out.print(ss);
           list.add(ss);
        }
        //关闭流
        br.close();

        //遍历集合方式1
        /*Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();
            System.out.println(str);
        }*/

        //方式2
        for(String s:list){
            System.out.println(s);
        }
    }
}

结果:

public class ArrayListToTextDemo {
    public static void main(String[] args) throws IOException {
        //创建集合
        ArrayList<String> list = new ArrayList<String>();
        //创建字符缓冲输出流
        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

        //添加集合
        list.add("hello");
        list.add("world");
        list.add("java");

        for(String s:list){
            bw.write(s);
            //刷新缓冲区
            bw.flush();
            //换行
            bw.newLine();
        }
        //关闭流
        bw.close();
    }
}
随机获取文件中姓名

分析:
通过题目的意思我们可以知道如下的一些内容,
1.数据源是一个文本文件。
2.目的地是一个集合。
3.创建随机数
5.将文件的数据读取到集合中。
6.然后在获取一个随机数,在随机获取集合值

数据源:
     a.txt  -- FileReader -- BufferedReader
目的地:
      ArrayList

代码演示

public class GetNameDemo {
    public static void main(String[] args) throws IOException {
        //封装数据源
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        //目的地
        ArrayList<String> list = new ArrayList<>();
        //创建一个随机数
        Random r = new Random();

        //一次读取一行
        String line = null;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        for (int x = 0; x < 10; x++) {
            //获取随机名字
            System.out.println(list.get(r.nextInt(list.size())));

        }
    }
}

结果:

影流之主 劫
落日狂沙 疾风剑豪
至高之拳 李青
法外狂徒 格雷福斯
至高之拳 李青
复制单级文件

把D:\demo文件夹下的文件复制到E:\demo
复制文件:要先把数据源,和目的地文件夹路径先封装好。怎么封装要根据题目需求.
注意:目标如果文件夹不存在,需要我们创建,文件就不需要我们创建了,自动创建。

分析:
         1.封装文件夹
         2:封装目的地
         3:获取该文件下所有文件
         4.遍历文件对象数组
         ...
 数据源:
        D:\demo -- FileInputStream -- BufferedInputStream
 目的地:
        E:\demo -- FileOutputStream -- BufferedOutputStream

代码演示

public class CopyFolderDemo {
    public static void main(String[] rgs) {
        //封装文件夹
        File f = new File("D:\\demo");
        File f2 = new File("E:\\demo");
        //如果目标文件夹不存在就先创建
        if (!f2.exists()) {
            //注意:目标如果文件不存在,需要我们创建,文件就不需要我们创建了,自动创建。
            f2.mkdir();
        }
        //获取该文件夹下所有文件对象
        File[] files = f.listFiles();
        for (File file : files) {
            //System.out.println(file);//D:\demo\e.mp3
            //获取文件名称
            String fileName = file.getName();//e.mp3
            //拼接目的地文件
            File newFile = new File(f2,fileName);//E:\demo\e.mp3
            //调用复制文件方法
            copyFolder(file,newFile);
        }
    }

    //复制单级文件
    public static void copyFolder(File file, File newFile) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //封装文件夹下的文件
            bis = new BufferedInputStream(new FileInputStream(file));
            //封装目的地
            bos = new BufferedOutputStream(new FileOutputStream(newFile));
            //一次读取一个字节数组
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

在这里插入图片描述

复制指定目录下的指定文件,并修改后缀名。

需求:复制指定目录下的指定文件,并修改后缀名。
指定的文件是:.java文件。
指定的后缀名是:.jad
指定的目录是:jad

 分析:
        1.封装数据源
        2.封装目的地
        3.获取数据源的文件对象数组
        4.遍历文件对象数组
                判断是否是文件
                       是:判断是否是以java结尾
                                是:将文件后缀名改为.jad
                                        在把封装的目的地和改后文件拼接成一个新的File对象
                                        在调用复制方法
                                否:
                           
                       否:不搭理

数据源:e:\javase\A.java
目的地:d:\jadse\A.jad

代码演示1(不使用文件过滤器)

public class CopyRenameJavaDemo {
    public static void main(String[] args) {
        //封装数据源
        File f1 = new File("E:\\javase");
        //封装目的地
        File f2 = new File("D:\\jad");

        //判断如果文件夹不存就创建
        if (!f2.exists()) {
            f2.mkdir();
        }

        //获取数据源下的所有文件对象
        File[] files = f1.listFiles();

        //遍历文件对象数组
        for (File file : files) {
            //判断是否是文件
            if (file.isFile()) {
                //判断文件是否是以java结尾的
                if (file.getName().endsWith(".java")) {
                   //System.out.println(file);//E:\javase\A.java
                    //将文件转化为.jad
                    String name = file.getName().replace(".java", ".jad");//A.jad
                    File newFile = new File(f2, name);
                    //调用方法
                    copyJavaFile(file,newFile);
                }
            }
        }
    }

    //复制文件
    public static void copyJavaFile(File file, File newFile) {
        //封装数据源
        BufferedInputStream bis = null;
        //封装目的地
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(newFile));
            //一次读取一个字节数组
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:
在这里插入图片描述

代码演示2(使用文件过滤器)

分析:
        1.封装数据源
        2.封装目的地
        3.使用文件过滤器过滤文件
        4.遍历文件数组
            把目的地拼接文件名称
        5.调用复制文件方法  
public class CopyRenameJavaDemo2 {
    public static void main(String[] args) {
        //封装数据源
        File f1 = new File("E:\\javase");
        //封装目的地
        File f2 = new File("D:\\jad");

        //如果文件夹不存在就创建
        if(!f2.exists()){
            f2.mkdir();
        }
        //获取数据源文件对象,返回的师傅符合条件的文件了
        File[] files = f1.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                /*System.out.println(dir);
                System.out.println(name);
                 File file  = new File(dir,name);
                boolean b1 = file.isFile();
                boolean b2 = name.endsWith(".java");
                return b1&&b2;*/
                return new File(dir, name).isFile() && name.endsWith(".java");
            }
        });
        //遍历文件数组
        for (File file : files) {
            System.out.println(file);//E:\javase\A.java
            File newFile = new File(f2, file.getName());//D:\jad\A.java
            copyJavaFolder(file,newFile);
        }
    }
    //复制文件方法
    public static void copyJavaFolder(File file, File newFile) {
        //封装数据源
        BufferedInputStream bis = null;
        //封装目的地
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(newFile));
            //一次读取一个字节数组
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:
在这里插入图片描述

复制多级文件夹和文件

开始复制的时候没有demos,这个文件也复制的。

分析:
        1.封装数据源
        2.封装目的地
        3.调用复制多级文件的方法
       	4.判断是否是文件夹
       			是:递归调用方法
       			否:调用文件文件功能
数据源:D:\MyWorkSpace\basic-code\demos
目的地:E:\\

代码演示

public class CopyDuoJiFolder2 {
    public static void main(String[] args) {
        //封装数据源
        File f1 = new File("D:\\MyWorkSpace\\basic-code\\demos");
        //封装目的地
        File f2 = new File("E:\\");
        copyDouJiFolder(f1, f2);
    }
    //调用复制多级目录方法
    public static void copyDouJiFolder(File srcFolder, File tarFolder) {
        if (srcFolder.isDirectory()) {
            //是目录
            //System.out.println(srcFolder);D:\MyWorkSpace\basic-code\demos
            File newfile = new File(tarFolder, srcFolder.getName());
            //System.out.println(file);
            //该文件是否存在
            if (!newfile.exists()) {
                newfile.mkdir();
            }
            //获取该文件中所有对象
            File[] files = srcFolder.listFiles();
            //遍历
            for (File f : files) {
                //调用递归方法
                copyDouJiFolder(f, newfile);//递归出口
            }
        } else {
            //是文件
            // D:\MyWorkSpace\basic-code\demos\d.txt
            File newFile = new File(tarFolder, srcFolder.getName());
            //调用复制文件的方法
            copyFile(srcFolder,newFile);
        }
    }
    //复制文件方法
    public static void copyFile(File srcFolder, File tarFolder) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFolder));
            bos = new BufferedOutputStream(new FileOutputStream(tarFolder));
            //一次读取一个字节数组
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:
在这里插入图片描述

键盘录入学生信息按照总分排序并写入文本文件

实现方式1

 分析:
        1:创建一个存储学生的集合TreeSet
        2:键盘录入5个学生信息
        3.读取集合中的学生信息
数据源:
    TreeSet
目的地:
    a.txt.txt文件

代码演示1(TreeSet集合的方式)

public class CopyStudentToFileDemo {
    public static void main(String[] args) throws IOException {

        //创建集合对象
        TreeSet<Student> list = new TreeSet<>(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.getAge() - s2.getAge() : num3;
                return num4;
            }
        });

        for (int x = 1; x <= 5; x++) {
            //创建键盘录入对象
            System.out.println("--------录入学生信息开始--------");
            Scanner sc = new Scanner(System.in);
            System.out.print("录入第" + x + "个学生姓名:");
            String name = sc.nextLine();
            System.out.print("录入第" + x + "个学生年龄:");
            String age = sc.nextLine();
            System.out.print("录入第" + x + "个学生语文成绩:");
            String chinese = sc.nextLine();
            System.out.print("录入第" + x + "个学生数学成绩:");
            String math = sc.nextLine();
            System.out.print("录入第" + x + "个学生英语成绩:");
            String english = sc.nextLine();

            Student s = new Student();
            //设置学生姓名
            s.setName(name);
            //设置学生年龄
            s.setAge(Integer.parseInt(age));
            //设置学生语文成绩
            s.setChinese(Integer.parseInt(chinese));
            //设置学生数学成绩
            s.setMath(Integer.parseInt(math));
            //设置学生英语成绩
            s.setEnglish(Integer.parseInt(english));

            list.add(s);
        }

        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
        bw.write("姓名\t年龄\t语文成绩\t数学成绩\t英语成绩");
        bw.newLine();
        //遍历集合
        for (Student s : list) {
            bw.write(s.getName() + "\t" + s.getAge() + "\t" + s.getChinese() +
                    "\t" + s.getMath() + "\t" + s.getEnglish());
            bw.newLine();
            bw.flush();

        }
         //关闭流
        bw.close();
    }
}

结果:a.txt文件中的内容

姓名	年龄	语文成绩	数学成绩	英语成绩
小武	11	130	120	111
小明	12	111	123	99
小凤	14	111	123	90
小飞	13	111	122	77
小丽	11	130	60	11

实现方式2

 分析:
        1:创建一个存储学生的集合ArrayList集合
        2:键盘录入5个学生信息
        3.读取集合中的学生信息
数据源:
    ArrayList
目的地:
    a.txt.txt文件

代码演示2(ArrayList集合的方式)

public class CopyStudentToFileDemo2 {
    public static void main(String[] args) throws IOException {
        ArrayList<Student> list = new ArrayList<>();
        //ArrayList集合排序
        Collections.sort(list, 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.getAge() - s2.getAge() : num3;
                return num4;
            }
        });

        for (int x = 1; x <= 5; x++) {
            //创建键盘录入对象
            System.out.println("--------录入学生信息开始--------");
            Scanner sc = new Scanner(System.in);
            System.out.print("录入第" + x + "个学生姓名:");
            String name = sc.nextLine();
            System.out.print("录入第" + x + "个学生年龄:");
            String age = sc.nextLine();
            System.out.print("录入第" + x + "个学生语文成绩:");
            String chinese = sc.nextLine();
            System.out.print("录入第" + x + "个学生数学成绩:");
            String math = sc.nextLine();
            System.out.print("录入第" + x + "个学生英语成绩:");
            String english = sc.nextLine();

            Student s = new Student();
            //设置学生姓名
            s.setName(name);
            //设置学生年龄
            s.setAge(Integer.parseInt(age));
            //设置学生语文成绩
            s.setChinese(Integer.parseInt(chinese));
            //设置学生数学成绩
            s.setMath(Integer.parseInt(math));
            //设置学生英语成绩
            s.setEnglish(Integer.parseInt(english));

            list.add(s);
        }

        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
        bw.write("姓名\t年龄\t语文成绩\t数学成绩\t英语成绩");
        bw.newLine();
        //遍历集合
        for (Student s : list) {
            bw.write(s.getName() + "\t" + s.getAge() + "\t" + s.getChinese() +
                    "\t" + s.getMath() + "\t" + s.getEnglish());
            bw.newLine();
            bw.flush();
        }
        //关闭流
        bw.close();
    }
}

结果:a.txt文件中的内容

姓名	年龄	语文成绩	数学成绩	英语成绩
小武	11	130	120	111
小明	12	111	123	99
小凤	14	111	123	90
小飞	13	111	122	77
小丽	11	130	60	11
复制文件并将内容排序

已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
请编写程序读取数据内容,把数据排序后写入ss.txt中。

分析:
          1:封装数据源
          2:封装目的地
          3:读取字符串数据
          4:将读取到字符串数据转化为字符数组
          5:排序字符数组
          6:将字符数组转化为字符串
          7:写到ss.txt文件中
数据源:
   ss.txt
目的地:
   s.txt

代码演示

public class CopySortStringDemo {
    public static void main(String[] args) {
        //封装数据源
        BufferedReader br = null;
        //封装目的地
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader("s.txt"));
            bw = new BufferedWriter(new FileWriter("ss.txt"));
            //一次读取一行
            String line =null;
            //读取一行的数据
            line = br.readLine();
            //将读取到的数据转化为字符数组
            char[] chars = line.toCharArray();
            //对数组进行排序
            Arrays.sort(chars);
            //写一行数据
            bw.write(new String(chars));
            //关闭流
            br.close();
            bw.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

abcdefghijklmnopqrstuvwxyz
自定义类模拟BufferedReader的readLine()功能

代码实现
MyBufferedReader测试类

public class MyBufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        //创建自定义流对象
        MyBufferedReader mbr = new MyBufferedReader(new FileReader("a.txt"));

        String line =null;
        while ((line=mbr.readLine())!=null){
            System.out.print(line);
        }
		//关闭资源
        mbr.close();
    }
}

自定义MyBufferedReader类

public class MyBufferedReader {
    Reader r;
    public MyBufferedReader(Reader r){
        this.r = r;
    }

    //实现一次读取一行的方法
    public String readLine() throws IOException {
        /*
         * 我要返回一个字符串,我该怎么办呢? 必须去看看r对象能够读取什么东西呢? 两个读取方法,一次读取一个字符或者一次读取一个字符数组
         * 那么,要返回一个字符串,用哪个方法比较好呢? 我们很容易想到字符数组比较好,但是问题来了,就是这个数组的长度是多长呢?
         * 根本就没有办法定义数组的长度一行的数据是有变化的,你定义多长都不合适。 所以,只能选择一次读取一个字符。
         * 但是呢,这种方式的时候,我们再读取下一个字符的时候,上一个字符就丢失了 所以,我们又应该定义一个临时存储空间把读取过的字符给存储起来。
         * 这个用谁比较和是呢?数组,集合,字符串缓冲区三个可供选择。
         * 经过简单的分析,最终选择使用字符串缓冲区对象。并且使用的是StringBuilder
         */
        StringBuffer sb = new StringBuffer();
        int ch = 0;
        while ((ch = r.read())!=-1){
        	//因为\r\n是一个回车键组成部分,需要逐个判断。
            if(ch=='\r'){,
                continue;
            }
            if(ch=='\n'){
				//已经到结尾
                return sb.append((char)ch).toString();
            }
            //未到结尾继续添加数据
            sb.append((char)ch);
        }

        //如果没有读到换行符,字符串缓冲区可能还有值。加一个判断
        if(sb.length()>0){
            return sb.toString();
        }
        return null;
    }
    
    public void close() throws IOException {
        r.close();
    }
}
自定义类模拟LineNumberReader的获取行号功能

代码演示1(不使用继承类演示)
MyLineNumberReader测试类

public class MyLineNumberReaderDemo {
    public static void main(String[] args) throws IOException {
        MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader("a.txt"));
        //没有读数据不能计算行号
        System.out.println(mlnr.getLineNumber());
        System.out.println(mlnr.getLineNumber());
        System.out.println(mlnr.getLineNumber());
        String line = null;
        while ((line=mlnr.readLine())!=null){
            System.out.print(mlnr.getLineNumber()+"-"+line);
        }
    }
}

自定义MyLineNumberReader类

public class MyLineNumberReader {
    Reader r;
    int lineNumber = 0;

    public MyLineNumberReader(Reader r) {
        this.r = r;
    }

    //获取行号
    public int getLineNumber() {
        //注意lineNumber++不能放在这里,因为只有真的读取到了数据才能增加行号
        return lineNumber;
    }

    //设置行号方法
    public void setLineNumber(int lineNumber) {
        this.lineNumber = lineNumber;
    }

    //一次读取一行的方法
    public String readLine() throws IOException {
        //还有读取数据了才能计算行号
        lineNumber++;
        StringBuffer sb = new StringBuffer();
        int ch = 0;
        //因为\r\n是一个回车键组成部分,需要逐个判断。
        while ((ch = r.read()) != -1) {
            //只有读取到了数据我才做++
            if (ch == '\r') {
                continue;
            }
            if (ch == '\n') {
                //已经到结尾
                return sb.append((char) ch).toString();
            }
            //未到结尾继续添加数据
            sb.append((char) ch);
        }
        //如果没有读到换行符,字符串缓冲区可能还有值。加一个判断
        if (sb.length() > 0) {
            return sb.toString();
        }
        return null;
    }

    //关闭资源
    public void close() throws IOException {
        r.close();
    }
}

结果:

0
0
0
1-hello
2-world
3-java

代码演示2(使用继承类演示)
MyLineNumberReader测试类

public class MyLineNumberReaderDemo {
    public static void main(String[] args) throws IOException {
        MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader("a.txt"));
        //没有读数据不能计算行号
        System.out.println(mlnr.getLineNumber());
        System.out.println(mlnr.getLineNumber());
        System.out.println(mlnr.getLineNumber());
        String line = null;
        while ((line=mlnr.readLine())!=null){
            System.out.print(mlnr.getLineNumber()+"-"+line);
        }
        //关闭资源
        mlnr.close();
    }
}

自定义MyLineNumberReader去继承MyBufferedReader类

public class MyLineNumberReader extends MyBufferedReader {

    int lineNumber = 0;

    public MyLineNumberReader(Reader r) {
        super(r);
    }

    //获取行号
    public int getLineNumber() {
        //注意lineNumber++不能放在这里,因为只有真的读取到了数据才能增加函数
        return lineNumber;
    }

    //设置行号方法
    public void setLineNumber(int lineNumber) throws IOException {
        this.lineNumber = lineNumber;
    }

    //重写reabLine()方法
    @Override
    public String readLine() throws IOException {
        //只有读取了才增加行号
        lineNumber++;
        return super.readLine();
    }
}

自定义MyBufferedReader类

public class MyBufferedReader {
    Reader r;
    public MyBufferedReader(Reader r){
        this.r = r;
    }

    //实现一次读取一行的方法
    public String readLine() throws IOException {
        /*
         * 我要返回一个字符串,我该怎么办呢? 必须去看看r对象能够读取什么东西呢? 两个读取方法,一次读取一个字符或者一次读取一个字符数组
         * 那么,要返回一个字符串,用哪个方法比较好呢? 我们很容易想到字符数组比较好,但是问题来了,就是这个数组的长度是多长呢?
         * 根本就没有办法定义数组的长度一行的数据是有变化的,你定义多长都不合适。 所以,只能选择一次读取一个字符。
         * 但是呢,这种方式的时候,我们再读取下一个字符的时候,上一个字符就丢失了 所以,我们又应该定义一个临时存储空间把读取过的字符给存储起来。
         * 这个用谁比较和是呢?数组,集合,字符串缓冲区三个可供选择。
         * 经过简单的分析,最终选择使用字符串缓冲区对象。并且使用的是StringBuilder
         */
        StringBuffer sb = new StringBuffer();
        int ch = 0;
        while ((ch = r.read())!=-1){
        	//因为\r\n是一个回车键组成部分,需要逐个判断。
            if(ch=='\r'){,
                continue;
            }
            if(ch=='\n'){
				//已经到结尾
                return sb.append((char)ch).toString();
            }
            //未到结尾继续添加数据
            sb.append((char)ch);
        }

        //如果没有读到换行符,字符串缓冲区可能还有值。加一个判断
        if(sb.length()>0){
            return sb.toString();
        }
        return null;
    }
    
    public void close() throws IOException {
        r.close();
    }
}

结果:

0
0
0
1-hello
2-world
3-java
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值