资讯专栏INFORMATION COLUMN

Java编程基础20——异常&IO(File类)

church / 2129人阅读

摘要:异常异常的概述和分类异常的概述异常就是程序在运行过程中出现的错误。运行时异常就是程序员所犯的错误,需要回来修改代码。获取异常类名和异常信息,返回字符串。如果路径名不同,就是改名并剪切。删除注意事项中的删除不走回收站。

1_异常(异常的概述和分类)

A:异常的概述

异常就是Java程序在运行过程中出现的错误。

B:异常的分类

通过API查看Throwable

Error

服务器宕机,数据库崩溃等

Exception

C:异常的继承体系

* Throwable
    * Error    
    * Exception
        * RuntimeException
2_异常(JVM默认是如何处理异常的)

A:JVM默认是如何处理异常的

main函数收到这个问题时,有两种处理方式:

a:自己将该问题处理,然后继续运行

b:自己没有针对的处理方式,只有交给调用main的jvm来处理

jvm有一个默认的异常处理机制,就将该异常进行处理.

并将该异常的名称,异常的信息.异常出现的位置打印在了控制台上,同时将程序停止运行

B:案例演示

JVM默认如何处理异常

public class Demo1_Exception {
    public static void main(String[] args) {
//        demo1();
        Demo d = new Demo();
        int x = d.div(10, 0);        //new ArithmeticException(/ by zero)  除数是0,违反算数运算法则
        System.out.println(x);
    }
    private static void demo1() { 
        int[] arr = {11,22,33,44,55};
//        arr = null;                    //NullPointerException            空指针异常
        System.out.println(arr[10]);    //ArrayIndexOutOfBoundsException    数组索引越界异常
    }
}
class Demo{
    public int div(int a,int b) {
        return a / b;
    }
}
3_异常(try...catch的方式处理异常1)

A:异常处理的两种方式

a:try…catch…finally

try catch

try catch finally

try finally

b:throws

B:try...catch处理异常的基本格式

try…catch…finally

C:案例演示

try...catch的方式处理1个异常

public class Demo2_Exception {
    /* try:用来检测异常
     catch:用来捕获异常的
     finally:释放资源
     当通过trycatch将异常处理,程序继续向下执行*/
    public static void main(String[] args) {
        Demo2 d = new Demo2();
        try {
            int x = d.div(10, 0);
            System.out.println(x);
        }catch(ArithmeticException a) {
            System.out.println("出错了,除数为0了");
        }
        System.out.println("----------");
    }
}
class Demo2{
    public int div(int a,int b) {
        return a / b;
    }
}
4_异常(try...catch的方式处理异常2)

A:案例演示

try...catch的方式处理多个异常

JDK7以后处理多个异常的方式及注意事项

public class Demo3_Exception {
//安卓:客户端开发,如何处理异常?try{}catch(Exception e) {}
//JavaEE:服务端开发,一般都是底层开发,从底层向上抛
    public static void main(String[] args) {
//        demo1();
        int a = 10;
        int b = 0;
        int[] arr = {11,22,33,44,55};
        //JdK7如何处理多个异常
        try {
            System.out.println(a / b);
            System.out.println(arr[10]);
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println("出错了");
        } 
    }

    private static void demo1() {
        int a = 10;
        int b = 0;
        int[] arr = {11,22,33,44,55};
        try {
            System.out.println(a / b);
            System.out.println(arr[10]);
            arr = null;
            System.out.println(arr[0]);
        } catch (ArithmeticException e) {
            System.out.println("除数不能为零");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("索引越界了");
        } catch (Exception e) {                //Exception e = new NullPointerException();
            System.out.println("出错了");
        }
        System.out.println("over");
    }
}
5_异常(编译期异常和运行期异常的区别)

A:编译期异常和运行期异常的区别

Java中的异常被分为两大类:编译时异常和运行时异常。

所有的RuntimeException类及其子类的实例被称为运行时异常,其他的异常就是编译时异常

编译时异常

Java程序必须显示处理,否则程序就会发生错误,无法通过编译

运行时异常

无需显示处理,也可以和编译时异常一样处理

B:案例演示

编译期异常和运行期异常的区别

import java.io.FileInputStream;
public class Demo4_Exception {
/*
编译时异常:也叫健壮性异常,不处理编译通不过。
运行时异常:就是程序员所犯的错误,需要回来修改代码。
*/    
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("xxx.txt");
        } catch (Exception e) {
    
        }
    }
}
6_异常(Throwable的几个常见方法)

A:Throwable的几个常见方法

a:getMessage()

获取异常信息,返回字符串。

b:toString()

获取异常类名和异常信息,返回字符串。

c:printStackTrace()

获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。

B:案例演示

Throwable的几个常见方法的基本使用

public class Demo5_throwable {
    public static void main(String[] args) {
        try {
            System.out.println(1/0);
        } catch (Exception e) {        //Exception e = new ArithmeticException(" / by zero");
//            System.out.println(e.getMessage());            //获取异常信息
            System.out.println(e);                        //调用toString方法,打印异常类名和异常信息
            e.printStackTrace();                        //jvm默认就用这种方式处理异常
        }
    }
}
7_异常(throws的方式处理异常)

A:throws的方式处理异常

定义功能方法时,需要把出现的问题暴露出来让调用者去处理。

那么就通过throws在方法上标识。

B:案例演示

举例分别演示编译时异常和运行时异常的抛出

public class Demo6_Exception {
//编译时异常的抛出必须对其进行处理
//运行时异常的抛出可以处理也可以不处理

    public static void main(String[] args) throws Exception {
        Person p = new Person();
        p.setAge(-17);
        System.out.println(p.getAge());
    }
}

class Person{
    private String name;
    private int age;
    public Person() {
        super();
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) throws RuntimeException {
        if(age > 0 && age <= 150) {
            this.age = age;
        }else {
            throw new RuntimeException("年龄非法");
//            System.out.println("请回火星吧");
        }
    }
}
8_异常(throw的概述以及和throws的区别)

A:throw的概述

在功能方法内部出现某种情况,程序不能继续运行,需要进行跳转时,就用throw把异常对象抛出。

B:案例演示

分别演示编译时异常对象和运行时异常对象的抛出

C:throws和throw的区别

a:throws

用在方法声明后面,跟的是异常类名

可以跟多个异常类名,用逗号隔开

表示抛出异常,由该方法的调用者来处理

b:throw

用在方法体内,跟的是异常对象名

只能抛出一个异常对象名

表示抛出异常,由方法体内的语句处理

9_异常(finally关键字的特点及作用)

A:finally的特点

被finally控制的语句体一定会执行

特殊情况:在执行到finally之前jvm退出了(比如System.exit(0))

B:finally的作用

用于释放资源,在IO流操作和数据库操作中会见到

C:案例演示

finally关键字的特点及作用

public static void main(String[] args) {
        try {
            System.out.println(10/0);
        } catch (Exception e) {
            System.out.println("除数为零了");
            System.exit(0);            //退出jvm虚拟机
            return;
        } finally {
            System.out.println("看看我执行了吗");
        }        
    }
10_异常(finally关键字的面试题)

A:面试题1

final,finally和finalize的区别

final可以修饰类不能被继承,修饰方法不能被重写,修饰变量只能赋值一次

finally是try语句中的一个语句体,不能多带带使用,用来释放资源

finalize是一个方法,当垃圾回收器确定不存在该对象的更多引用时,由对象的垃圾回收器调用此方法。

B:面试题2

如果catch里面有return语句,请问finally的代码还会执行吗?如果会,请问是在return前还是return后。

public class Demo8_test {
    public static void main(String[] args) {
        Demo3 d = new Demo3();
        System.out.println(d.method());
    }
}
class Demo3 {
    public int method() {
        int x = 10;
        try {
            x = 20;
            System.out.println(1/0);
            return x;
        } catch (Exception e) {
            x = 30;
            return x;
        } finally {
            x = 40;
        }
    }
}
11_异常(自定义异常概述和基本使用)

A:为什么需要自定义异常

举例:人的年龄

B:自定义异常概述

继承自Exception

继承自RuntimeException

C:案例演示

自定义异常的基本使用

class AgeOutOfBoundsException extends RuntimeException {
    public AgeOutOfBoundsException() {
        super();        
    }

    public AgeOutOfBoundsException(String message) {
        super(message);    
    }
}
    public void setAge(int age) throws AgeOutOfBoundsException {
        if(age > 0 && age <= 150) {
            this.age = age;
        }else {
            throw new AgeOutOfBoundsException("年齡非法");
        }
    }
12_异常(异常的注意事项及如何使用异常处理)

A:异常注意事项

a:子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。(父亲坏了,儿子不能比父亲更坏)

b:如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常

c:如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws

B:如何使用异常处理

原则:如果该功能内部可以将问题处理,用try,如果处理不了,交由调用者处理,这是用throws

区别:

后续程序需要继续运行就try

后续程序不需要继续运行就throws

如果JDK没有提供对应的异常,需要自定义异常。

13_异常(练习)

键盘录入一个int类型的整数,对其求二进制表现形式

如果录入的整数过大,给予提示,录入的整数过大请重新录入一个整数BigInteger

如果录入的是小数,给予提示,录入的是小数,请重新录入一个整数

如果录入的是其他字符,给予提示,录入的是非法字符,请重新录入一个整数

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;
public class Demo10_test {    
/** 分析
     * 1.创建键盘录入对象
     * 2.将键盘录入的结果存储在String类型的字符串中,存储int类型中,如果有不符合条件的直接报错,无法进行后续判断
     * 3.是键盘录入的结果转换成int类型的数据,是正确的还是错误的。
     * 4.正确的直接转换
     * 5.错误的要对应的判断
     * */ 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        while(true) {
            String line = sc.nextLine();                    //将键盘录入的结果存储在line中
            try {
                int num = Integer.parseInt(line);                //将字符串转换为整数
                System.out.println(Integer.toBinaryString(num));//将整数转换为二进制
                break;                                            //跳出循环
            } catch (Exception e) {
                try {
                    new BigInteger(line);
                    System.out.println("录入错误,您录入的是一个过大的整数,请重新输入:");    
                } catch (Exception e2) {                        //Alt + Shift + z
                    try {
                        new BigDecimal(line);
                        System.out.println("录入错误,您录入的是一个小数,请重新输入:");
                    } catch (Exception e3) {
                        System.out.println("录入错误,您录入的是非法字符,请重新输入:");
                    }
                }
            }
        }
//        BigInteger big = new BigInteger("123");
    }
}
14_File类(File类的概述和构造方法)

A:File类的概述

File更应该叫做一个路径

文件路径或者文件夹路径

路径分为绝对路径和相对路径

绝对路径是一个固定的路径,从盘符开始

相对路径相对于某个位置,在eclipse下是指当前项目下,在dos下

查看API指的是当前路径

文件和目录路径名的抽象表示形式

B:构造方法

File(String pathname):根据一个路径得到File对象

File(String parent, String child):根据一个目录和一个子文件/目录得到File对象

File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象

C:案例演示

File类的构造方法

import java.io.File;
public class Demo1_File {
    public static void main(String[] args) {
//        demo1();
//        demo2();
        File parent = new File("C:UsersalbertDesktopJavaGuide-masterJava相关");
        String child = "ArrayList.md";
        File file = new File(parent, child);
        System.out.println(file.exists());
        System.out.println(parent.exists());
    }

    private static void demo2() {
        String parent = "C:UsersalbertDesktopJavaGuide-masterJava相关";
        String child = "ArrayList.md";
        File file = new File(parent,child);
        System.out.println(file.exists());
    }

    private static void demo1() {
        File file = new File("C:UsersalbertDesktopJavaGuide-masterJava相关");
        System.out.println(file.exists());
        
        File file2 = new File("xxx.txt");
        System.out.println(file2.exists());
    }
}
15_File类(File类的创建功能)

A:创建功能

public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了

public boolean mkdir():创建文件夹 如果存在这样的文件夹,就不创建了

public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来

B:案例演示

File类的创建功能

注意事项:

如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。

import java.io.File;
import java.io.IOException;
public class Demo2_FileMethod {
    public static void main(String[] args) throws IOException {
//        demo1();
        File dir1 = new File("aaa");
        System.out.println(dir1.mkdir());
        
        File dir2 = new File("bbb.txt");
        System.out.println(dir2.mkdir());
        
        File dir3 = new File("cccffffd");
        System.out.println(dir3.mkdirs());                    //创建多级目录
    }

    private static void demo1() throws IOException {
        File file = new File("yyy.txt");                    //创建文件
        System.out.println(file.createNewFile());            //如果没哟就创建,返回true
        
        File file2 = new File("zzz");
        System.out.println(file2.createNewFile());
    }
}
16_File类(File类的重命名和删除功能)

A:重命名和删除功能

public boolean renameTo(File dest):把文件重命名为指定的文件路径

public boolean delete():删除文件或者文件夹

B:重命名注意事项

如果路径名相同,就是改名。

如果路径名不同,就是改名并剪切。

C:删除注意事项:

Java中的删除不走回收站。

要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹

import java.io.File;
public class Demo3_FileMethod {
    public static void main(String[] args) {
//        demo1();
        File file1 = new File("yyy.txt");
        System.out.println(file1.delete());
        
        File file2 = new File("aaa");
        System.out.println(file2.delete());
        
        File file3 = new File("ccc");            //被删除的文件必须为空
        System.out.println(file3.delete());
    }

    private static void demo1() {
        File file1 = new File("ooo.txt");
        File file2 = new File("D:xxx.txt");
        System.out.println(file1.renameTo(file2));
    }
}
17_File类(File类的判断功能)

A:判断功能

public boolean isDirectory():判断是否是目录

public boolean isFile():判断是否是文件

public boolean exists():判断是否存在

public boolean canRead():判断是否可读

public boolean canWrite():判断是否可写

public boolean isHidden():判断是否隐藏

B:案例演示

File类的判断功能

import java.io.File;
public class Demo4_FileMethod {
    public static void main(String[] args) {
//        demo1();
        File file = new File("zzz");
        file.setReadable(false);                //windows认为所有的文件都是可读的
        System.out.println(file.canRead());
        
        file.setWritable(true);
        System.out.println(file.canWrite());    //windows系统可以设置为不可写
        
        File file2 = new File("lalala.txt");
        System.out.println(file2.isHidden());    //判断是否是隐藏文件
    }

    private static void demo1() {
        File dir1 = new File("ccc");
        System.out.println(dir1.isDirectory());        //判断是否是文件夹
        
        File dir2 = new File("zzz");
        System.out.println(dir2.isDirectory());
        
        System.out.println(dir1.isFile());            //判断是否是文件
        System.out.println(dir2.isFile());
    }
}
18_File类(File类的获取功能)

A:获取功能

public String getAbsolutePath():获取绝对路径

public String getPath():获取路径

public String getName():获取名称

public long length():获取长度。字节数

public long lastModified():获取最后一次的修改时间,毫秒值

public String[] list():获取指定目录下的所有文件或者文件夹的名称数组

public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组

B:案例演示

File类的获取功能

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo5_FileMethod {
    public static void main(String[] args) {
//        demo1();
        File dir = new File("E:JavaworkJavaSE_File");
        String[] arr = dir.list();                    //仅为了获取文件名
        for (String string : arr) {
            System.out.println(string);
        }
        
        File[] subFiles = dir.listFiles();
        for (File file : subFiles) {                //获取文件对象
            System.out.println(file);
        }
    }

    private static void demo1() {
        File file1 = new File("ccc.txt");
        File file2 = new File("E:JavaworkJavaSE_Fileccc.txt");
//        System.out.println(file1.getAbsolutePath());        //获取绝对路径
//        System.out.println(file2.getAbsolutePath());
        
//        System.out.println(file1.getPath());                //获取构造方法中传入的路径
//        System.out.println(file2.getPath());
        
//        System.out.println(file1.getName());
//        System.out.println(file2.getName());                //获取文件或文件夹的名称
        
//        System.out.println(file1.length());
//        System.out.println(file2.length());
        
        Date d = new Date(file1.lastModified());            //文件的最后修改时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        System.out.println(sdf.format(d));
        System.out.println(file2.lastModified());
    }
}
19_File类(输出指定目录下指定后缀的文件名)

A:案例演示

需求:判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称

import java.io.File;
public class Demo6_test {
    /** A:案例演示
    * 需求:判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称*/
    public static void main(String[] args) {
        File dir = new File("E:");
        /*String[] arr = dir.list();                //获取E盘下所有文件及文件夹
        for (String string : arr) {
            if(string.endsWith(".jpg")) {
                System.out.println(string);
            }
        }*/
        
        File[] subFiles = dir.listFiles();        //获取E盘下所有的文件和文件夹对象
        for (File subFile : subFiles) {
            if(subFile.isFile() && subFile.getName().endsWith(".jpg")) {
                System.out.println(subFile);
            }
        }
    }
}
20_File类(文件名称过滤器的概述及使用)

A:文件名称过滤器的概述

public String[] list(FilenameFilter filter)

public File[] listFiles(FileFilter filter)

B:文件名称过滤器的使用

需求:判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称

C:源码分析

带文件名称过滤器的list()方法的源码

        File dir = new File("E:");
        String[] arr = dir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
//                System.out.println(dir);
//                System.out.println(name);
                File file = new File(dir, name);
                return file.isFile() && file.getName().endsWith(".jpg");
            }
        });
        for (String string : arr) {
            System.out.println(string);
        }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77286.html

相关文章

  • Java编程基础22——IO(字符流)&amp;字符流其他内容&amp;递归

    摘要:字符流字符流是什么字符流是可以直接读写字符的流字符流读取字符就要先读取到字节数据然后转为字符如果要写出字符需要把字符转为字节再写出类的方法可以按照字符大小读取通过项目默认的码表一次读取一个字符赋值给将读到的字符强转后打印字符流类的方法可以 1_字符流FileReader 1.字符流是什么 字符流是可以直接读写字符的IO流 字符流读取字符, 就要先读取到字节数据, 然后转为字符. ...

    BoYang 评论0 收藏0
  • 《 Kotlin + Spring Boot : 下一代 Java 服务端开发 》

    摘要:下一代服务端开发下一代服务端开发第部门快速开始第章快速开始环境准备,,快速上手实现一个第章企业级服务开发从到语言的缺点发展历程的缺点为什么是产生的背景解决了哪些问题为什么是的发展历程容器的配置地狱是什么从到下一代企业级服务开发在移动开发领域 《 Kotlin + Spring Boot : 下一代 Java 服务端开发 》 Kotlin + Spring Boot : 下一代 Java...

    springDevBird 评论0 收藏0
  • Java learn 02 OO &amp; Exception

    摘要:可处理中成员变量和参数重名的情况。可看作是一个变量,它的值是当前对象的引用声明的成员变量为成员变量,它为该类的公用变量,在第一次使用时被初始化。经常出,不用逮压路面上的小石子异常是提供的用于处理程序中错误的一种机制。 Chap 3 Java OO focus on : * 对象和类的概念 * 类 (对类) 之间的关系 * 面向对象...

    mzlogin 评论0 收藏0
  • Java IO框架总揽--ObjectInputStream&amp; ObjectOutputSt

    摘要:与的作用是对基本数据和对象进行序列化操作进行支持。如果检测到反序列化的类的和对象二进制流的不同,则会抛出异常。 ObjectInputStream与ObjectOutputStream的作用是:对基本数据和对象进行序列化操作进行支持。其中ObjectInputStream对象提供对基本数据和对象对持久存储,当我们需要读取这些存储这些基本数据或对象时,可以创建文件输入流对应的Object...

    philadelphia 评论0 收藏0
  • Java编程基础15——正则表达式&amp;常用工具

    摘要:正则表达式的概述和简单使用正则表达式是指一个用来描述或者匹配一系列符合某个语法规则的字符串的单个字符串。例如,在表达式中,存在四个这样的组组零始终代表整个表达式。 1_正则表达式的概述和简单使用 A:正则表达式 是指一个用来描述或者匹配一系列符合某个语法规则的字符串的单个字符串。其实就是一种规则。有自己特殊的应用。 作用:比如注册邮箱,邮箱有用户名和密码,一般会对其限制长度,这个...

    miqt 评论0 收藏0

发表评论

0条评论

church

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<