javaseday27异常、FIle、综合案例

异常

小结

编译时异常和运行时异常

小结

异常在代码中的作用

public class Demo1 {
    public static void main(String[] args) {
        Student[] arr = new Student[3];
        //由于没有给数组赋值所以数组中为null
        //访问空数组出现空指针异常 NullPointerException
        System.out.println(arr[0].getName());
    }
}
public class Demo2 {
    public static void main(String[] args) {
        Student2 s1 = new Student2("张三,21");
        //由于给的字符串的分隔符和构造函数中的不同导致没有进行分割,出现数组访问越界异常
        //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
        //	at MyException.Student2.<init>(Student2.java:12)
        //	at MyException.Demo2.main(Demo2.java:5)
        /**
         *     public Student2(String s) {
         *         String[] split = s.split("-");
         *         this.name = split[0];
         *         this.age = Integer.parseInt(split[1]);
         *     }
         *     分隔符为- 输入的为 , 因此出现异常
         */
        System.out.println(s1);
    }
}
public class DEmo3 {
    public static void main(String[] args) {
        Student s1 = new Student();
        //给age赋值超过其要求的范围
        /*
        报错的异常
        Exception in thread "main" java.lang.RuntimeException
	        at MyException.Student.setAge(Student.java:47)
	        at MyException.DEmo3.main(DEmo3.java:7)

	//代码
	public void setAge(int age) {
        //限制范围为18-40
        if (age<18||age>40){
            //向上抛出运行时异常
            throw new RuntimeException();
        }else {
            this.age = age;
        }
    }
         */
        s1.setAge(50);
    }
}

异常的处理方式

JVM默认的处理方式

public class Demo4 {
    public static void main(String[] args) {
        System.out.println("hhhhhhhhhhhh");
        /**
         * Exception in thread "main" java.lang.ArithmeticException: / by zero
         * 	at MyException.Demo4.main(Demo4.java:6)
         * hhhhhhhhhhhh
         * JVM处理异常,打印到控制台,程序停止运行
         */
        System.out.println(2/0);
        System.out.println("aaaaaaaaaa");
        System.out.println("ssssssssss");
    }
}

自己处理(捕获异常)

public class ExceptionDemo6 {
    public static void main(String[] args) {
        /*
            自己处理(捕获异常)
            格式:
                try {
                   可能出现异常的代码;
                } catch(异常类名 变量名) {
                   异常的处理代码;
                }
             好处:可以让程序继续往下执行,不会停止
         */


        int[] arr = {1, 2, 3, 4, 5, 6};
        try{
            //可能出现异常的代码;
            System.out.println(arr[10]);//此处出现了异常,程序就会在这里创建一个ArrayIndexOutOfBoundsException对象
                                        //new ArrayIndexOutOfBoundsException();
                                        //拿着这个对象到catch的小括号中对比,看括号中的变量是否可以接收这个对象
                                        //如果能被接收,就表示该异常就被捕获(抓住),执行catch里面对应的代码
                                        //当catch里面所有的代码执行完毕,继续执行try...catch体系下面的其他代码
        }catch(ArrayIndexOutOfBoundsException e){
            //如果出现了ArrayIndexOutOfBoundsException异常,我该如何处理
            System.out.println("索引越界了");
        }

        System.out.println("看看我执行了吗?");

    }
}
灵魂四问

异常中的常见方法

public class Demo6 {
    public static void main(String[] args) {
        int[] arr = new int[3];
        try {
            System.out.println(arr[10]);
            /**
             * 数组访问错误出现异常,ArrayIndexOutOfBoundsException。
             * 这里是否执行
             */
        } catch (ArrayIndexOutOfBoundsException e) {
            //方法一
//            String message = e.getMessage();//Index 10 out of bounds for length 3
//            System.out.println(message);
            //方法二
//            String str = e.toString();//java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
//            System.out.println(str);

            //方法三
            e.printStackTrace();
            /**
             * java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3
             * 	at MyException.Demo6.main(Demo6.java:7)
             * 	底层是调用了System.err.println进行输出
             * 	把异常的错误信息以红色字体的形式打印在控制台
             * 	细节:只打印错误信息,不会停止查询的运行
             */

        }
        System.out.println("这里是否执行");
    }
}

抛出异常

    public static void main(String[] args) {
//        int[] arr = {1,2,3,4};
//        int[] arr = {};
        int[] arr = null;

        try {
            int max = max(arr);
            System.out.println(max);
        } catch (NullPointerException e) {
            System.out.println("传入的数组为null");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("传入的数组为空");
        }


    }
    //获取最大值
    public static int max(int[] arr){
        //对传入的数据进行判断
        if (arr==null){
            throw new NullPointerException();
        }
        if (arr.length==0){
            throw new ArrayIndexOutOfBoundsException();
        }
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (max<arr[i]){
                max = arr[i];
            }
        }
        return max;
    }

练习:键盘录入数据

package MyException.Test;

public class Womam {
    private String name;
    private int age;

    public Womam() {
    }

    public Womam(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Womam{name = " + name + ", age = " + age + "}";
    }
}
package MyException.Test;

import java.util.Scanner;

public class Test1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        boolean flag = true;

        while (flag) {
            try {
                System.out.println("请输入姓名");
                String name = sc.next();
                System.out.println("请输入年龄");
                String age = sc.next();
                put(name,age);
                flag = false;
            }catch (NumberFormatException e){
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    public static Womam put(String name,String age) throws Exception {
        //判断姓名是否符合规则
        if (name.length()<3||name.length()>10){
            throw new Exception("输入的姓名不符合规则");
        }
        //判断年龄是否符合要求
        int agei = 0;
        try {
            agei = Integer.parseInt(age);
        } catch (NumberFormatException e) {
            throw new NumberFormatException("年龄录入的不是数字");
        }
        if (agei<18||agei>40){
            throw new Exception("年龄的大小不符合要求");
        }
        Womam w = new Womam(name,agei);
        return w;

    }

}

新方法

public class Test2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Womam w = new Womam();

        while (true) {
            try {
                System.out.println("请输入姓名");
                String name = sc.next();
                System.out.println("请输入年龄");
                String agestr = sc.next();
                w.setName(name);
                int age = Integer.parseInt(agestr);
                w.setAge(age);
                //如果没有出错则执行跳出循换,出错则不可执行
                break;
            } catch (NumberFormatException e) {
                System.out.println("你输入的年龄的格式有问题");
            }catch (RuntimeException e){
                System.out.println("您输入的姓名或年龄的范围有问题");
            }
        }
        System.out.println(w);
    }
}
//修改了set方法,添加了对数据的校验判断

public class Womam {
    private String name;
    private int age;

    public Womam() {
    }

    public Womam(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        //对姓名进行判断
        if (name.length()<3||name.length()>10){
            throw new RuntimeException();
        }
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        //对年龄进行判断
        if (age<18||age>40){
            throw new RuntimeException();
        }
        this.age = age;
    }

    public String toString() {
        return "Womam{name = " + name + ", age = " + age + "}";
    }
}

自定义异常

public class NameException extends RuntimeException{
    //继承RuntimeException并重新两个构造方法
    public NameException() {
    }

    public NameException(String message) {
        super(message);
    }
}
public class AgeException extends RuntimeException{
    //继承RuntimeException并重新两个构造方法
    public AgeException() {
    }

    public AgeException(String message) {
        super(message);
    }
}
package MyException.Test;

public class Womam {
    private String name;
    private int age;

    public Womam() {
    }

    public Womam(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        //对姓名进行判断
        if (name.length()<3||name.length()>10){
            throw new NameException(name+"输入错误");
        }
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
        //对年龄进行判断
        if (age<18||age>40){
            throw new AgeException(age+"输入错误");
        }
        this.age = age;
    }

    public String toString() {
        return "Womam{name = " + name + ", age = " + age + "}";
    }

}
package MyException.Test;

import java.util.Scanner;

public class Test2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Womam w = new Womam();

        while (true) {
            try {
                System.out.println("请输入姓名");
                String name = sc.next();
                System.out.println("请输入年龄");
                String agestr = sc.next();
                w.setName(name);
                int age = Integer.parseInt(agestr);
                w.setAge(age);
                //如果没有出错则执行跳出循换,出错则不可执行
                break;
            } catch (NumberFormatException e) {
                System.out.println("你输入的年龄的格式有问题");
            }catch (NameException e){
                e.printStackTrace();
            }catch (AgeException e){
                e.printStackTrace();
            }
        }
        System.out.println(w);
    }
}

File

文件保存的位置:路径

构造方法

public class Demo1 {
    public static void main(String[] args) {
        String s1 = "C:\\Users\\20724\\Desktop\\a.txt";
        File f1 = new File(s1);
        System.out.println(f1);
        //第二种构造方法
        String preans = "C:\\Users\\20724\\Desktop";
        String chiled = "a.txt";
        File f2 = new File(preans,chiled);
        System.out.println(f2);
        //第三种构造方法,使用父路径的File对象和子路径的String字符串创建
        String preans2 = "C:\\Users\\20724\\Desktop";
        File prean= new File(preans2);
        String chiled2 = "a.txt";
        File f3 = new File(prean,chiled2);
        System.out.println(f3);

    }
}

小结

常见的成员变量

public class Demo2 {
    public static void main(String[] args) {
        String s1 = "C:\\Users\\20724\\Desktop\\FileTest\\a.txt";
        String s2 = "C:\\Users\\20724\\Desktop\\FileTest\\bbb";
        String s3 = "C:\\Users\\20724\\Desktop\\FileTest\\yyy";
        //获取文件的File对象
        File f1 = new File(s1);
        //获取文件夹的File对象
        File f2 = new File(s2);
        //获取不存在路径文件对象
        File f3 = new File(s3);

        //对文件路径进行判断
        System.out.println(f1.isDirectory());//false
        System.out.println(f1.isFile());//ture
        System.out.println(f1.exists());//ture
        System.out.println("===============================");
        //对文件夹路径进行判断
        System.out.println(f2.isDirectory());//ture
        System.out.println(f2.isFile());//fales
        System.out.println(f2.exists());//ture
        System.out.println("================================");
        //对不存在的文件路径进行判断
        System.out.println(f3.isDirectory());//fales
        System.out.println(f3.isFile());//fales
        System.out.println(f3.exists());//fales


    }
}

public class Demo3 {
    public static void main(String[] args) {
        String s1 = "C:\\Users\\20724\\Desktop\\FileTest\\a.txt";
        String s2 = "C:\\Users\\20724\\Desktop\\FileTest\\bbb";
        String s3 = "C:\\Users\\20724\\Desktop\\FileTest\\yyy";
        //获取文件的File对象
        File f1 = new File(s1);
        //获取文件夹的File对象
        File f2 = new File(s2);
        //获取不存在路径文件对象
        File f3 = new File(s3);

        /**
         * length 方法,只对文件有效,无法返回文件夹的大小
         */
        System.out.println(f1.length());//15
        System.out.println(f2.length());//0
        System.out.println(f3.length());//0
        System.out.println("===============================");
        /**
         * getAbsolutePath 方法 返回绝对地址,可用于获取相对地址文件的绝对地址
         */
        System.out.println(f1.getAbsolutePath());//C:\Users\20724\Desktop\FileTest\a.txt
        System.out.println(f2.getAbsolutePath());//C:\Users\20724\Desktop\FileTest\bbb
        System.out.println(f3.getAbsolutePath());//C:\Users\20724\Desktop\FileTest\yyy
        System.out.println("================================");
        /**
         * 获取创建文件对象时传入的地址
         */
        System.out.println(f1.getPath());
        System.out.println(f2.getPath());
        System.out.println(f3.getPath());
        System.out.println("================================");
        /**
         * 文件则返回 文件名+后缀
         * 文件夹返回 文件夹名
         */
        System.out.println(f1.getName());//a.txt
        System.out.println(f2.getName());//bbb
        System.out.println(f3.getName());//yyy
        System.out.println("================================");
        System.out.println(f1.lastModified());
        System.out.println(f2.lastModified());
        System.out.println(f3.lastModified());
        System.out.println("================================");
        System.out.println("================================");
        /**
         * 课堂小作业
         */
        long l = f1.lastModified();
        SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        date.setTime(l);
        System.out.println(sdf.format( date));
    }
}

File的常见方法

public class FileDemo4 {
    public static void main(String[] args) throws IOException {
      /*
        public boolean createNewFile()      创建一个新的空的文件
        public boolean mkdir()              创建单级文件夹
        public boolean mkdirs()             创建多级文件夹
        public boolean delete()             删除文件、空文件夹
      */


        //1.createNewFile 创建一个新的空的文件
        //细节1:如果当前路径表示的文件是不存在的,则创建成功,方法返回true
        //      如果当前路径表示的文件是存在的,则创建失败,方法返回false
        //细节2:如果父级路径是不存在的,那么方法会有异常IOException
        //细节3:createNewFile方法创建的一定是文件,如果路径中不包含后缀名,则创建一个没有后缀的文件
        /*File f1 = new File("D:\\aaa\\ddd");
        boolean b = f1.createNewFile();
        System.out.println(b);//true*/


        //2.mkdir   make Directory,文件夹(目录)
        //细节1:windows当中路径是唯一的,如果当前路径已经存在,则创建失败,返回false
        //细节2:mkdir方法只能创建单级文件夹,无法创建多级文件夹。
      /*  File f2 = new File("D:\\aaa\\aaa\\bbb\\ccc");
        boolean b = f2.mkdir();
        System.out.println(b);*/

        //3.mkdirs   创建多级文件夹
        //细节:既可以创建单级的,又可以创建多级的文件夹
        File f3 = new File("D:\\aaa\\ggg");
        boolean b = f3.mkdirs();
        System.out.println(b);//true

    }
}
public class FileDemo5 {
    public static void main(String[] args) {
      /*
        public boolean delete()             删除文件、空文件夹
        细节:
            如果删除的是文件,则直接删除,不走回收站。
            如果删除的是空文件夹,则直接删除,不走回收站
            如果删除的是有内容的文件夹,则删除失败
      */


        //1.创建File对象
        File f1 = new File("D:\\aaa\\eee");
        //2.删除
        boolean b = f1.delete();
        System.out.println(b);


    }
}

成员方法(获取并遍历)

    public static void main(String[] args) {
        String f1 = "C:\\Users\\20724\\Desktop\\FileTest";
        File fl1 = new File(f1);

        File[] files = fl1.listFiles();
        for (File file : files) {
            System.out.println(file.getAbsolutePath());
        }

    }

    public static void main(String[] args) {
        String f1 = "C:\\Users\\20724\\Desktop\\FileTest";
        File fl1 = new File(f1);
//将以txt结尾的文件留下
        File[] files = fl1.listFiles();
        for (File file : files) {
           if (file.getName().endsWith(".txt")){
               System.out.println(file.getAbsolutePath());
           }
        }
    }

//了解即可
public class Demo6 {
    public static void main(String[] args) {
        String f1 = "C:\\Users\\20724\\Desktop\\FileTest";
        File fl1 = new File(f1);
        //获取电脑的盘符信息listRoots
        File[] files = File.listRoots();
        for (File file : files) {
            System.out.println(file);
        }
        //获取当前路径下的全部内容的名字
        String[] list = fl1.list();
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("===================");
        //使用文件名过滤器获得所有以txt结尾的文件名
        String[] list1 = fl1.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".txt")) {
                    return true;
                }
                return false;
            }
        });
        for (String s : list1) {
            System.out.println(s);
        }
        System.out.println("==============================");
        File[] files1 = fl1.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (pathname.getName().endsWith(".txt")) {
                    return true;
                }
                return false;
            }
        });
        for (File file : files1) {
            System.out.println(file.getName());

        }
        System.out.println("===============================");

        File[] files2 = fl1.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".txt")) {
                    return true;
                }
                return false;
            }
        });
        for (File file : files2) {
            System.out.println(file.getName());
        }


    }
}

综合练习

练习一:

public class Test {
    public static void main(String[] args) throws IOException {
        //获取当前模块的文件对象
        File f1 = new File("javaseday27");
        //遍历获取到的文件数组判断是否有aaa文件夹
        File[] files = f1.listFiles();
        for (File file : files) {
            //找到对应的文件名
            if (file.getName().equals("aaa")){
                //判断文件名是否为文件夹
                if (file.isDirectory()){
                    //开始创建文件
                    //创建一个a.txt文件的文件对象
                    File fa = new File(file,"a.txt");
                    System.out.println(fa.createNewFile());
                }
            }
        }
    }
}

练习二:

public class Test {
    public static void main(String[] args) {
        //获取指定文件夹的File对象
        File f1 = new File("C:\\Users\\20724\\Desktop\\FileTest");
        System.out.println(haveAvi(f1));
    }
    public static boolean haveAvi(File f1){
        //获取其中所有的文件列表
        File[] files = f1.listFiles();
        //遍历数组进行判断
        for (File file : files) {
            if (file.getName().endsWith(".avi")&&file.isFile()) {
                System.out.println(file.getName());
                return true;
            }
        }
        return false;
    }
}

练习三:

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

            //获取指定文件夹的File对象
            findAVI();
    }

    public static void findAVI(){
        File[] arr = File.listRoots();
        for (File file : arr) {
            haveavi(file);
        }
    }
    public static void haveavi(File f1){
        //进入文件对象
        File[] files = f1.listFiles();
        //判断对象是否为空
        if (files != null){
            //遍历文件中的数据
            for (File file : files) {
                if (file.isFile()){
                    //判断是否是文件
                    if (file.getName().endsWith(".avi")){
                        System.out.println(file.getName());
                    }
                }else {
                    //判断是否是文件夹
                    haveavi(file);
                }
            }
        }
    }
}

练习四:

 

package File.Test.Test4;

import java.io.File;

public class Test {
    public static void main(String[] args) {
        //定义一个方法使用递归的方法来进行删除操作

        File f1 = new File("C:\\Users\\20724\\Desktop\\FileTest\\bbb");
        delect(f1);
    }
    public static void delect(File f1){
        //判断是否为文件夹
        if (f1.isDirectory()){
            //是文件夹
            //判断是否为空
            if (f1.delete()){
                //删除成功则不操作
            }else {
                //失败则进行递归
                File[] files = f1.listFiles();
                for (File file : files) {
                    delect(file);
                }
                delect(f1);
            }
            //为空,则删除
            //不为空,则进行递归
        }else {
            //是文件直接删除
            System.out.println(f1.delete());
        }
    }
}

练习五:

public class Demo1 {
    public static void main(String[] args) {
        //统计文件夹的总大小
        File file = new File("C:\\Users\\20724\\Desktop\\FileTest");
        long filesize = Filesize(file);
        System.out.println(filesize);
    }
    public static long Filesize(File f1){
        long sum = 0;
        //判断是什么
        if (f1.isFile()){
            //获取大小并返回
            sum = f1.length()+sum;
        }else {
            File[] files = f1.listFiles();
            for (File file : files) {
              sum = Filesize(file)+sum;
            }
        }
        return sum;
    }
}

​​​​​​​

public class Test {
    public static void main(String[] args) {
        //统计文件夹的总大小
        File file = new File("C:\\Users\\20724\\Desktop\\FileTest");

        HashMap<String, Integer> hashMap = getclass(file);
        System.out.println(hashMap);

    }
    public static HashMap<String,Integer> getclass(File f1){
        HashMap<String,Integer> hm = new HashMap<>();
        if (f1.isFile()){
            //是文件判断格式
            String[] split = f1.getName().split("\\.");
            //防止有没有后缀的情况干扰
            if (split.length>=2){
                String st =  split[split.length-1];
                //判断是否包含了这些数据
                if (hm.containsKey(st)){
                    Integer i = hm.get(st);
                    hm.put(st,i+1);
                }else {
                    hm.put(st,1);
                }
            }
        }else {
            File[] files = f1.listFiles();
            for (File file : files) {
                HashMap<String, Integer> hashMap = getclass(file);
                //将hm和hashMap结合
                Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
                for (Map.Entry<String, Integer> entry : entries) {
                    String key = entry.getKey();
                    //判断是否有key
                    if (hm.containsKey(key)){
                        Integer i = hm.get(key);
                        hm.put(key,i+entry.getValue());
                    }else {
                        hm.put(key,entry.getValue());
                    }
                }
            }
        }
        return hm;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值