The latest Java basic series of courses--Day09-Exception handling & Application of File class

​ Author homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

​# day06—exception handling

1. Abnormal

1.1 Understanding anomalies

Next, let's learn about exceptions, which will help us deal with problems that may arise in the program. Let me introduce my classmates first, what is anomaly?

Let's read the following code and use this code to understand the exception. When we call a method, we often get an exception when we are careful, and then print some exception information on the console. In fact, the abnormal information printed is called abnormal.

Then some students must be wondering, I write codes every day with exceptions, I know this is an exception! We learn about exceptions here, in fact, to tell you how the exceptions are generated? You can avoid exceptions only if you know how they are generated. And how to deal with exceptions.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-vsUTRUHG-1690250314954)(assets/1667312695257.png)]

Because problems often occur when writing code, Java designers have written many exception classes for us to describe problems in different scenarios. And some classes are common, so there is an abnormal inheritance system

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-p30eJy09-1690250314956)(assets/1667313423356.png)]

Let's first demonstrate a runtime exception generation

int[] arr = {
    
    11,22,33};
//5是一个不存在的索引,所以此时产生ArrayIndexOutOfBoundsExcpetion
System.out.println(arr[5]); 

The figure below is the inheritance system of the ArrayIndexOutOfBoundsExcpetion class in the API, and tells us under what circumstances it is generated.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-yybGyCBh-1690250314957)(assets/1667313567748.png)]

Let's demonstrate a compile-time exception

When we call the parse method of the SimpleDateFormat object, the passed parameters must be consistent with the specified date format, otherwise an exception will occur. Java is more thoughtful. In order to remind the caller of the method more strongly, it designs a compile-time exception. It reminds the exception in advance. If there is really a problem with the method you call, as long as there may be a problem, it will report an exception to you (red wavy line).

The purpose of the exception at compile time: the meaning is to tell you, your boy pays attention! ! , be careful here and it is easy to make mistakes, check it carefully

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-dfTqpNgv-1690250314958)(assets/1667313705048.png)]

Someone said, I checked, I confirmed that my code is ok, in order for it not to report an error, continue to write the code. We have two solutions here.

  • The first one: use throws to declare on the method, which means to tell the next caller that there may be exceptions in it, so pay attention when you call.
/**
 * 目标:认识异常。
 */
public class ExceptionTest1 {
    
    
    public static void main(String[] args) throws ParseException{
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse("2028-11-11 10:24");
        System.out.println(d);
    }
}
  • The second method: use the try...catch statement block to handle exceptions.
public class ExceptionTest1 {
    
    
    public static void main(String[] args) throws ParseException{
    
    
        try {
    
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = sdf.parse("2028-11-11 10:24");
            System.out.println(d);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
    }
}

Well, let's get to know what an exception is.

1.2 Custom exceptions

Students have already understood what anomalies are after the study just now, but they cannot provide exception classes for all problems in the world. If an enterprise wants to express a certain problem through exceptions, then it is necessary to define exception classes by itself.

Let's demonstrate custom exceptions to you through an actual scenario.

Requirement: Write a saveAge(int age) method, and judge the parameter age in the method. If age<0 or >=150, the age is considered illegal. If the age is illegal, an illegal age exception will be thrown to the caller.

Analysis: There is no age exception in the Java API, so we can customize an exception class to indicate an illegal age exception, and then throw a custom exception in the method.

  • First write an exception class AgeIllegalException (this is the name I chose, the name is very nice), inherit
// 1、必须让这个类继承自Exception,才能成为一个编译时异常类。
public class AgeIllegalException extends Exception{
    
    
    public AgeIllegalException() {
    
    
    }

    public AgeIllegalException(String message) {
    
    
        super(message);
    }
}
  • Write another test class, define a saveAge(int age) method in the test class, and if the age is not between 0 and 150, an AgeIllegalException exception object will be thrown to the caller.
public class ExceptionTest2 {
    
    
    public static void main(String[] args) {
    
    
        // 需求:保存一个合法的年
        try {
    
    
            saveAge2(225);
            System.out.println("saveAge2底层执行是成功的!");
        } catch (AgeIllegalException e) {
    
    
            e.printStackTrace();
            System.out.println("saveAge2底层执行是出现bug的!");
        }
    }

	//2、在方法中对age进行判断,不合法则抛出AgeIllegalException
    public static void saveAge(int age){
    
    
        if(age > 0 && age < 150){
    
    
            System.out.println("年龄被成功保存: " + age);
        }else {
    
    
            // 用一个异常对象封装这个问题
            // throw 抛出去这个异常对象
            throw new AgeIllegalRuntimeException("/age is illegal, your age is " + age);
        }
    }
}
  • Note that custom exceptions may be compile-time exceptions or runtime exceptions
1.如果自定义异常类继承Excpetion,则是编译时异常。
	特点:方法中抛出的是编译时异常,必须在方法上使用throws声明,强制调用者处理。
	
2.如果自定义异常类继承RuntimeException,则运行时异常。
	特点:方法中抛出的是运行时异常,不需要在方法上用throws声明。

1.3 Exception handling

Students, through the study of the previous two sections, we have already known what is abnormal and the process of abnormal generation. Next, you need to tell the students how to deal with the exception.

For example, there are the following scenarios: A calls B, and B calls C; an exception occurs in C and is thrown to B, and an exception occurs in B and then thrown to A; it is not recommended to throw the exception when it reaches A, because the JVM handler will terminate the exception when the exception is finally thrown, and the user will not understand the exception information, and the experience is very bad.

A better approach at this time is: 1. Capture the exception and display friendly information to the user; 2. Try to execute it again to see if the problem can be fixed.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-c7AOqHXY-1690250314960)(assets/1667315686041.png)]

Let's look at a code. The main method calls the test1 method, and the test1 method calls the test2 method. There are many exceptions thrown in the test1 and test2 methods.

  • The first way is to catch and process the exception in the main method with try...catch, and give a friendly reminder.
public class ExceptionTest3 {
    
    
    public static void main(String[] args)  {
    
    
        try {
    
    
            test1();
        } catch (FileNotFoundException e) {
    
    
            System.out.println("您要找的文件不存在!!");
            e.printStackTrace(); // 打印出这个异常对象的信息。记录下来。
        } catch (ParseException e) {
    
    
            System.out.println("您要解析的时间有问题了!");
            e.printStackTrace(); // 打印出这个异常对象的信息。记录下来。
        }
    }

    public static void test1() throws FileNotFoundException, ParseException {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse("2028-11-11 10:24:11");
        System.out.println(d);
        test2();
    }

    public static void test2() throws FileNotFoundException {
    
    
        // 读取文件的。
        InputStream is = new FileInputStream("D:/meinv.png");
    }
}
  • The second way is to catch the exception in the main method and try to fix it
/**
 * 目标:掌握异常的处理方式:捕获异常,尝试修复。
 */
public class ExceptionTest4 {
    
    
    public static void main(String[] args) {
    
    
        // 需求:调用一个方法,让用户输入一个合适的价格返回为止。
        // 尝试修复
        while (true) {
    
    
            try {
    
    
                System.out.println(getMoney());
                break;
            } catch (Exception e) {
    
    
                System.out.println("请您输入合法的数字!!");
            }
        }
    }

    public static double getMoney(){
    
    
        Scanner sc = new Scanner(System.in);
        while (true) {
    
    
            System.out.println("请您输入合适的价格:");
            double money = sc.nextDouble();
            if(money >= 0){
    
    
                return money;
            }else {
    
    
                System.out.println("您输入的价格是不合适的!");
            }
        }
    }
}

Ok, so far we have learned all about exceptions

2. File class

Next, the knowledge we want to learn is a File class. But before I talk about this knowledge point, I want to talk about something else with my classmates. After the chat, it will be easier for you to come back to study File.

  • Let me ask you a question first, what solutions can you use to store data when writing code?

    The answer is shown in the figure below: it can be a variable, an array, an object, or a collection, but these data are stored in memory. As long as the program execution ends or a breakpoint is reached, the data will disappear. Cannot be permanently stored.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Ji9x4ILk-1690250314962)(assets/1667650170239.png)]

  • Some data needs to be stored for a long time, what should I do?

    The answer is shown in the figure below: the data can be stored in the hard disk in the form of a file, even if the program ends or a breakpoint occurs, as long as the hard disk is not damaged, the data will exist forever.

    [External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-YVQ4wmGq-1690250314963)(assets/1667650277680.png)]

The File class to be learned now is used to represent the files (or folders) under the current system. The methods provided by the File class can obtain the file size, determine whether the file exists, create a file, create a folder, etc.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-d7QVQ5RX-1690250314964)(assets/1667650503532.png)]

**But we need to pay attention: **The File object can only operate on the file, not the content in the file.

2.1 Creation of File objects

Learning the File class is the same as other classes, the first step is to create an object of the File class. To create an object, we have to see what constructors the File class has.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-UrY7O9qw-1690250314965)(assets/1667651303731.png)]

Let's demonstrate the code for creating objects in the File class

需求我们注意的是:路径中"\"要写成"\\", 路径中"/"可以直接用
/**
 * 目标:掌握File创建对象,代表具体文件的方案。
 */
public class FileTest1 {
    
    
    public static void main(String[] args) {
    
    
        // 1、创建一个File对象,指代某个具体的文件。
        // 路径分隔符
        // File f1 = new File("D:/resource/ab.txt");
        // File f1 = new File("D:\\resource\\ab.txt");
        File f1 = new File("D:" + File.separator +"resource" + File.separator + "ab.txt");
        System.out.println(f1.length()); // 文件大小

        File f2 = new File("D:/resource");
        System.out.println(f2.length());

        // 注意:File对象可以指代一个不存在的文件路径
        File f3 = new File("D:/resource/aaaa.txt");
        System.out.println(f3.length());
        System.out.println(f3.exists()); // false

        // 我现在要定位的文件是在模块中,应该怎么定位呢?
        // 绝对路径:带盘符的
        // File f4 = new File("D:\\code\\javasepromax\\file-io-app\\src\\itheima.txt");
        // 相对路径(重点):不带盘符,默认是直接去工程下寻找文件的。
        File f4 = new File("file-io-app\\src\\itheima.txt");
        System.out.println(f4.length());
    }
}

2.2 File judgment and acquisition method

Dear students, when we created the File object just now, we will pass a file path. However, it is not clear whether the path encapsulated by the File object exists or does not exist, whether it is a file or a folder. Fortunately, the File class provides methods to help us make judgments.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-FOYXSENe-1690250314967)(assets/1667659321570.png)]

Not much to say, just go to the code

/**
     目标:掌握File提供的判断文件类型、获取文件信息功能
 */
public class FileTest2 {
    
    
    public static void main(String[] args) throws UnsupportedEncodingException {
    
    
        // 1.创建文件对象,指代某个文件
        File f1 = new File("D:/resource/ab.txt");
        //File f1 = new File("D:/resource/");

        // 2、public boolean exists():判断当前文件对象,对应的文件路径是否存在,存在返回true.
        System.out.println(f1.exists());

        // 3、public boolean isFile() : 判断当前文件对象指代的是否是文件,是文件返回true,反之。
        System.out.println(f1.isFile());

        // 4、public boolean isDirectory()  : 判断当前文件对象指代的是否是文件夹,是文件夹返回true,反之。
        System.out.println(f1.isDirectory());
    }
}

In addition to the judgment function, there are some acquisition functions, see the code

File f1 = new File("D:/resource/ab.txt");

// 5.public String getName():获取文件的名称(包含后缀)
System.out.println(f1.getName());

// 6.public long length():获取文件的大小,返回字节个数
System.out.println(f1.length());

// 7.public long lastModified():获取文件的最后修改时间。
long time = f1.lastModified();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(time));

// 8.public String getPath():获取创建文件对象时,使用的路径
File f2 = new File("D:\\resource\\ab.txt");
File f3 = new File("file-io-app\\src\\itheima.txt");
System.out.println(f2.getPath());
System.out.println(f3.getPath());

// 9.public String getAbsolutePath():获取绝对路径
System.out.println(f2.getAbsolutePath());
System.out.println(f3.getAbsolutePath());

2.3 Create and delete methods

Just now a classmate asked the teacher, can we not create a file or folder without Java code? The answer is yes, not only can create but also delete.

The File class provides methods to create and delete files, not much to say, see the code.

/**
 * 目标:掌握File创建和删除文件相关的方法。
 */
public class FileTest3 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        // 1、public boolean createNewFile():创建一个新文件(文件内容为空),创建成功返回true,反之。
        File f1 = new File("D:/resource/itheima2.txt");
        System.out.println(f1.createNewFile());

        // 2、public boolean mkdir():用于创建文件夹,注意:只能创建一级文件夹
        File f2 = new File("D:/resource/aaa");
        System.out.println(f2.mkdir());

        // 3、public boolean mkdirs():用于创建文件夹,注意:可以创建多级文件夹
        File f3 = new File("D:/resource/bbb/ccc/ddd/eee/fff/ggg");
        System.out.println(f3.mkdirs());

        // 3、public boolean delete():删除文件,或者空文件,注意:不能删除非空文件夹。
        System.out.println(f1.delete());
        System.out.println(f2.delete());
        File f4 = new File("D:/resource");
        System.out.println(f4.delete());
    }
}

have to be aware of is:

1.mkdir(): 只能创建单级文件夹、
2.mkdirs(): 才能创建多级文件夹
3.delete(): 文件可以直接删除,但是文件夹只能删除空的文件夹,文件夹有内容删除不了。

2.4 Traverse folder method

Someone said, is there a way to get the contents of a folder? There are also, and we will learn two such methods below.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-iOVatIwh-1690250314968)(assets/1667659732559.png)]

Not much to say on the code, demonstrate

/**
 * 目标:掌握File提供的遍历文件夹的方法。
 */
public class FileTest4 {
    
    
    public static void main(String[] args) {
    
    
        // 1、public String[] list():获取当前目录下所有的"一级文件名称"到一个字符串数组中去返回。
        File f1 = new File("D:\\course\\待研发内容");
        String[] names = f1.list();
        for (String name : names) {
    
    
            System.out.println(name);
        }

        // 2、public File[] listFiles():(重点)获取当前目录下所有的"一级文件对象"到一个文件对象数组中去返回(重点)
        File[] files = f1.listFiles();
        for (File file : files) {
    
    
            System.out.println(file.getAbsolutePath());
        }

        File f = new File("D:/resource/aaa");
        File[] files1 = f.listFiles();
        System.out.println(Arrays.toString(files1));
    }
}

Here are a few issues to pay attention to

1.当主调是文件时,或者路径不存在时,返回null
2.当主调是空文件夹时,返回一个长度为0的数组
3.当主调是一个有内容的文件夹时,将里面所有一级文件和文件夹路径放在File数组中,并把数组返回
4.当主调是一个文件夹,且里面有隐藏文件时,将里面所有文件和文件夹的路径放在FIle数组中,包含隐藏文件
5.当主调是一个文件夹,但是没有权限访问时,返回null

The basic operation of traversing folders is over. But if some students want to get the contents of the subfolders in the folder, they can't do it yet. But after learning the following recursive knowledge, it is easy to do.

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/131911227