• Java实验七


    前言

    本次我依然在每个实验题下面都简单的写了一下思路解析,如果不太会的话也希望大家照着敲一遍,这些东西要敲出来才能掌握啊,只是看会了其实离真的掌握还差好远,(┭┮﹏┭┮我就是血的教训,看别人的以为看懂了就懒得去敲了,实际上啥也不会)不要只是简单的Ctrl c + Ctrl v,如果有疑惑的地方也欢迎找我来探讨呀🎈。

    一、判断E盘指定目录下是否有后缀名为.jpg的文件,如果有就输出此文件名称。

    思路解析:

    本题就是关于File类方法的考察啦,知道方法是怎么用的应该就很容易做出来了

    • File类的list()方法,能够返回目录下的文件组成的字符串数组
    • String类的endwith(String str)方法,判断是否以str结尾

    源代码:

    public static void main(String[] args) {
        //创建一个代表的E盘的File对象,使用绝对路径
        File file = new File("D://");
        //利用File类的list方法返回E盘下的所有文件名称的数组
        String[] arr = file.list();
    
        //也可以不要count哦
        int count = 0;
        //遍历数组找到以.jpg结尾的文件名输出
        for(String str : arr){
            if(str.endsWith(".jpg")){
                count++;
                System.out.println(count+":"+str);
            }
        }
        if (count==0){
            System.out.println("没有找到以.jpg结尾的文件哦");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    二、分别使用字节流和字节缓冲流的两种读取方式实现对图片文件的复制操作并比较两种方式在复制时间上的效率。

    思路解析:

    本题考察时IO流的相关应用了,主要需要大家学会文件的读取与复制操作,其实读写操作比较固定大家多写几遍就会了。

    • 字节流 :FileInputStream,FileOutputStream
    • 缓冲流:BufferedInputStream,BufferedOutputStream

    源代码:

    public static void main(String[] args) throws Exception {
        //利用字节流复制文件,注意这里为了看起来更清晰没有用try/catch处理,具体处理方法参考下面缓冲流
        //创建两个文件对象,file为准备复制的文件,newFlie为复制生成的文件
        //这里的路径为相对路径,此时位于项目下,所以要将需要复制的文件放到项目下哦
        File file = new File("01.jpg");
        File newFlie = new File("02.jpg");
    
        //创建字节输入流与字节输出流
        FileInputStream fis1 = new FileInputStream(file);
        FileOutputStream fos1 = new FileOutputStream(newFlie);
    
        //字节数组用于存储输入流中的数据
        //这里的1024没有特殊含义实际上写多少都可以,只不过太小的话效率比较低,太大又浪费空间
        byte[] bytes = new byte[1024];
        //len用于记录输入的字节长度,如果为-1则结束
        int len = 0;
        //记录当前时间
        long starttime = System.currentTimeMillis();
        //如果 fis1.read(bytes)=-1,说明输入结束
        while ((len = fis1.read(bytes)) != -1) {
            //将字节数组输出,从0开始,到len
            fos1.write(bytes, 0, len);
        }
        //结束
        long endtime = System.currentTimeMillis();
        System.out.println("字节流运行时间:" + (endtime - starttime));
        //关闭流
        fis1.close();
        fos1.close();
    
    
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File file1 = new File("01.jpg");
            File newfile2 = new File("03.jpg");
    
            FileInputStream fis2 = new FileInputStream(file1);
            FileOutputStream fos2 = new FileOutputStream(newfile2);
    
            //将输入输出流传入缓冲流流
            bis = new BufferedInputStream(fis2);
            bos = new BufferedOutputStream(fos2);
    
            long starttime2 = System.currentTimeMillis();
            //前面已经定义了len与bytes这里省略
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            long endtime2 = System.currentTimeMillis();
            System.out.println("缓冲流运行时间:" + (endtime2 - starttime2));
    
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //只需要关闭缓冲流即可
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    三、编写一个程序,分别使用转换流、字符流和缓冲字符流拷贝一个文本文件。要求:

    • 分别使用InputStreamReader、OutputStreamWriter类和FileReader、FileWriter类用两种方式(字符和字符数组)进行拷贝。

    • 使用BufferedReader、BufferedWriter类的特殊方法进行拷贝。

    思路解析:

    又是应用相应的IO流读写问题,不难但一定要自己动手去写,反正步骤基本上都是一样的。

    源代码:

    public static void main(String[] args) {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        //被复制的文件
        File file = new File("txt.txt");
        try {
            //复制生成的文件
            File newfile1 = new File("txt1.txt");
    
            //创建字节流
            FileInputStream fis1 = new FileInputStream(file);
            FileOutputStream fos1 = new FileOutputStream(newfile1);
    
            //创建转换流
            isr = new InputStreamReader(fis1);
            osw = new OutputStreamWriter(fos1);
    
            //注意转换流用char数组读写
            char[] chars = new char[1024];
            int len = 0;
            while ((len = isr.read(chars)) != -1) {
                osw.write(chars, 0, len);
            }
    
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //复制生成的文件
            File newfile2 = new File("txt2.txt");
            //字符流
            fr = new FileReader(file);
            fw = new FileWriter(newfile2);
            int len = 0;
            char[] chars = new char[1024];
            while ((len = fr.read(chars)) != -1) {
                fw.write(chars, 0, len);
            }
    
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //复制生成的文件
            File newfile3 = new File("txt3.txt");
            //字符流
            FileReader fr1 = new FileReader(file);
            FileWriter fw1 = new FileWriter(newfile3);
            //缓冲字符流
            br = new BufferedReader(fr1);
            bw = new BufferedWriter(fw1);
            int len = 0;
            char[] chars = new char[1024];
            while ((len = br.read(chars)) != -1) {
                bw.write(chars, 0, len);
            }
    
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105

    四、编程序实现下列功能:

    • 向指定的txt文件中写入键盘输入的内容,然后再重新读取该文件的内容,显示到控制台上。

    • 键盘录入5个学生信息(姓名, 成绩),按照成绩从高到低追加存入上述的文本文件中。

    思路解析:

    • 要求通过键盘写入文件,那么可以考虑将输入的信息转化为byte[]数组再直接写入
    • 读取文件打印到控制台考虑用转换流,将字节流转化为字符流再输出
    • 学生信息按照成绩从高到低,可以想到TreeSet对学生进行排序存储

    源代码:

    public class S7_4 {
        public static void main(String[] args)  {
            Scanner scanner = new Scanner(System.in);
            //创建一个Treeset集合存放录入的5个学生,并以成绩排序
            TreeSet<Student> set = new TreeSet<>();
    
            for (int i = 0; i < 5; i++) {
                System.out.println("请输入姓名");
                String str = scanner.next();
                System.out.println("请输入成绩");
                int score = scanner.nextInt();
                //计入TreeSet集合
                set.add(new Student(str, score));
            }
    
            //得到五个学生的信息,按照成绩遍历加入到字符串
            String str = "";
            for (Student stu : set) {
                str += stu.toString()+"\n" ;
            }
    
            //输出流
            FileOutputStream fos = null;
            FileInputStream fis = null;
            InputStreamReader isr = null;
            try {
                fos = new FileOutputStream(new File("01.txt"));
                //得到字符串转化的字节数组
                byte[] bytes = str.getBytes();
                //直接写入文件,从0到length
                fos.write(bytes, 0, bytes.length);
                //读取文件
                fis = new FileInputStream(new File("01.txt"));
                isr = new InputStreamReader(fis);
               //输出文件内容
                int len = 0;
                char[] chars = new char[1024];
                while ((len = isr.read(chars))!=-1){
                    for(int i = 0;i<len;i++){
                        System.out.print(chars[i]);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (isr!=null){
                    try {
                        isr.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
    
        }
    }
    
    //定义Student类,实现Comparable接口泛型,之和Student比较
    class Student implements Comparable<Student>{
        String name;
        int score;
    
        public Student() {
            super();
        }
    
        public Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
    
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", score=" + score +
                    '}';
        }
    
        @Override
        public int compareTo(Student student) {
            //加符号为从高到低
            return -Integer.compare(this.score,student.score);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93

    五、复制指定目录中的指定类型(如.java)的文件到另一个目录中。

    思路解析:

    如果只是复制一个文件到另一个文件相信大家都已经会了,那么这题要求指定目录中的指定类型,那么怎么得到指定文件呢?

    • 可以想到File类的listFiles()方法,返回的是File数组,再加上getName()和endwith()方法,就可以找到需要复制的文件了吧。

    那么复制后的文件的路径又怎么定义呢?

    • 你想要存放的路径+需要复制的文件名不就是心生成文件的路径了吗

    源代码:

    public static void main(String[] args) throws Exception {
        //准备复制的目录
        File file = new File("D:\\Code\\javacode\\Javabase");
        //得到目录下的文件数组
        File[] files = file.listFiles();
        //遍历文件
        for (File f : files){
            //如果该文件以".txt"结尾则是需要复制的文件
            if (f.getName().endsWith(".txt")) {
                //这里用缓冲流,毕竟快嘛,但做人可别太快哈ψ(`∇´)ψ
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try {
                    //新建一个文件目标地址为"D:\\Downloads\\"+f.getName(),
                    // 这里的+f.getName()非常巧妙有没有,开始我也没想到
                    File newfile = new File("D:\\Downloads\\" + f.getName());
    
                    bis = new BufferedInputStream(new FileInputStream(f));
                    bos = new BufferedOutputStream(new FileOutputStream(newfile));
                    //常规的读写操作了,写了这么多遍不会还有人不会吧
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, len);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    bis.close();
                    bos.close();
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

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

    思路解析:

    • 给字符串排序我们可以想到先将字符串转化为字符数组,再将字符数组的各个字符冒泡排序就可,不过Arrays类中有现成的sort()方法,所以就不用手动去敲啦。

    源代码:

    public static void main(String[] args) throws Exception {
        //本题没用用try/catch/fially处理,但前面都写那么多遍了自己来一遍吧
        BufferedReader br = new BufferedReader(new FileReader("s.txt"));
        //读取改文件的内容,存储到一个字符串中
        String s = "hcexfgijkamdnoqrzstuvwybpl";
        //把字符串转换成字符数组
        char[] chs = s.toCharArray();
        //对字符数组进行排序
        Arrays.sort(chs);
        //把字符数组转换成字符串
        String s2 = new String(chs);
        //把字符串写入ss.txt文件
    
        //这里我直接用匿名的方式处理了,其实是与下面注释的三行等价的
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("ss.txt")));
    
        /*File newfile = new File("ss.txt");
        FileWriter fw = new FileWriter(newfile);
        BufferedWriter bw = new BufferedWriter(fw);*/
    
        bw.write(s2);
    
        br.close();
        bw.close();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    🎉文章到这里就结束了,感谢诸佬的阅读。🎉
    💕欢迎诸佬对文章加以指正,也望诸佬不吝点赞、评论、收藏加关注呀😘

  • 相关阅读:
    2、并行接口、协议和相关芯片介绍(8080、8060)
    01【数据库的介绍】
    IMX6ULL开发——第一个驱动程序
    【斗破年番】火火抱彩鳞把她整害羞啦!女王解锁新造型,身形丰满超有料
    标识符、关键字、数据类型(java基础)
    android 将数据库中的 BLOB 对象动态加载为 XML,并设置到 Android Activity 的内容视图上
    【Linux】shell命令以及运行原理和Linux权限详解
    基于51单片机的自动售货机Proteus仿真
    阿里面试官浅聊Java面试那些事
    Blog2:nchu-software-oop-2022-4+5+期中
  • 原文地址:https://blog.csdn.net/m0_69383623/article/details/128169461