Java I/O流 01

 文件IO·异常 和 File类

异常的概述和分类

* A:异常的概述
  * 异常就是Java程序在运行过程中出现的错误

* B:异常的分类
  * 用过API查看Throwable
  * Error
    * 服务器宕机,数据库崩溃等
  * Exception

* C:异常的继承体系
  * Throwable
    * Error
    * Exception
      * RuntimeException,运行时异常,一般都是程序员犯的错误

package com.heima.exception;

public class Demo1_Exception {

    public static void main(String[] args) {
        int[] arr = { 11, 22, 33, 44, 55 };
        // System.out.println(arr[10]); // java.lang.ArrayIndexOutOfBoundsException,索引越界异常
        // arr = null;
        // System.out.println(arr[0]); // java.lang.NullPointerException,空指针异常
    }
}
Exception

 

JVM默认是如何处理异常的

* A:JVM默认是如何处理异常的
  * main函数收到这个问题的时候,有两种处理方式
    * a:自己将该问题处理,然后继续运行
    * b:自己没有针对的处理方式,只有交给调用main的JVM来处理
  * JVM有一个默认的异常处理机制,就将该异常进行处理
  * 并将该异常的名称、异常的信息、异常出现的位置打印在控制台上,同时使程序停止运行

* B:案例演示
  JVM默认如何处理异常

package com.heima.exception;

public class Demo2_Exception {
    // 看运行时错误,从后往前看
    public static void main(String[] args) {
        Demo d = new Demo();
//         int x = d.div(10, 0);    //  java.lang.ArithmeticException
//         System.out.println(x);
        
        
    }
}
/*
 * a = 10, b = 0
 * 10 / 0 被除数为10,当除数为0时,违背了算数运算法则,抛出异常
 * ArithmeticException a = new ArithmeticException("/ by zero");
   System.out.println(a);
 */
class Demo {
    // 除法运算
    public int div(int a, int b) { 
        return a / b;  
    }
}
Exception

 

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

* A:异常处理的两种方式
  * a:try...catch...finally
    * try...catch
    * try...catch...finally
    * try...finally
  * b:throws

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

* C:案例演示
  * try...catch的方式处理一个异常

package com.heima.exception;

public class Demo3_Exception {
    /*
     * try:用来检测异常的 
     *         try内能执行多少代码就执行多少代码,
     *         一旦报错,就会判断是否是catch中的异常,
     *         如果是,就跳出try,执行catch内的语句;
     *         如果不是,就报错并使程序中止
     *         如果try中没有问题,不会执行catch中的代码
     * catch:用来捕获异常的 
     * finally:释放资源
     * 
     * 世界上最真情的相依就是你在try,我在catch,无论你发神马脾气,我都静静接受,默默处理
     * 
     * 当通过try  catch 将问题处理了,程序会继续执行
     */
    public static void main(String[] args) {
        Demo2 d = new Demo2();
        try {
            int x = d.div(10, 0);
            System.out.println(x);
        }     catch (ArithmeticException a) { // ArithmeticException a = new ArithmeticException();
            System.out.println("除数为0了");
        }
        
        System.out.println("-------------------");
    }
}

class Demo2 {
    public int div(int a, int b) {
        return a / b;
    }
}
try...catch

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

package com.heima.exception;

public class Demo4_Exception {
    /*
     * 安卓,客户端开发,如何处理异常?
     *         try{} catch(Exception e){}  只用一个Exception接收
     * Javaee,服务器开发,如何处理异常?
     *          throw  一般都是底层开发,从底层向上抛,在最顶层录入错误日志
     * 
     * try后面如果跟多个catch,那么小的异常放前面,大的异常放后面,
     *         因为,根据多态的原理,如果大的放前面,就会将所有的子类对象接收,后面的catch就没有意义了
     */
    public static void main(String[] args) {
        // demo1();
        // demo2();        
    }

    public static void demo2() {
        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 | ArrayIndexOutOfBoundsException e) { // JDK7新特性
            System.out.println("出错了");
        }
    }

    public static void demo1() {
        int a = 10;
        int b = 0;
        int[] arr = { 11, 22, 33, 44, 55 };

        try {
            System.out.println(a / b); // 这里已经出错了,所以try内之后的代码不会再执行
            System.out.println(arr[10]);
            arr = null;
            System.out.println(arr[0]);
            
        } catch (ArithmeticException e) { // 从上到下匹配,只匹配一个
            System.out.println("除数不能为0");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("索引越界");
        } catch (Exception e) { // 类似 多态
            System.out.println("出错了");
        }
        
        System.out.println("----------------");
    }
}
try...catch

 

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

* A:编译期异常和运行时异常的区别
  * Java中的异常被分为两大类:编译器异常和运行时异常
  * 所有的RuntimeException类及其子类的实例被称为运行时异常,其他的异常就是编译期异常

  * 编译期异常
    * Java程序必须显示处理,否则程序就会发送错误,无法通过编译

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

* B:案例演示
  * 编译期异常和运行期异常的区别

package com.heima.exception;

import java.io.FileInputStream;

public class Demo5_Exception {
    /*
     * 编译时异常:也叫做未雨绸缪式异常
     *     未雨绸缪:在做某些事情的时候要做某些准备
     * 
     * 编译时异常:在编译某个程序的时候,有可能会有这样那样的事情发生,比如文件找不到,
     *     这样的异常就必须在编译的时候处理,如果不处理,编译通不过
     * 
     * 运行时异常:就是程序员所犯的错误,需要回来修改代码
     */
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("xxx.txt");            
        } catch (Exception e) {
            
        }
        
    }
}
Exception

 

Throwable的即可常见方法

* A:Throwable的几个常见方法
  * a:getMessage()
    * 获取异常信息,返回字符串
  * b:toString()
    * 获取异常类名和异常信息,返回字符串
  * c:printStackTrace()
    * 获取异常类名和异常信息,以及异常出现再程序中的位置,返回void

* B:案例演示
  * Throwable的几个常见方法的基本使用

package com.heima.exception;

public class Demo6_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默认就用这种方式处理异常
        }
    }
}
Throwable

 

throws 的方式处理异常

* A:throws 的方式处理异常
  * 定义功能方法时,需要把出现的问题暴露出来,让调用者去处理
  * 那么就通过throws在方法上标识

* B:案例演示
  * 举例分别演示编译时异常和运行时异常的抛出
  * 编译时异常的抛出必须对其进行处理
  * 运行时异常的抛出可以不处理

package com.heima.exception;

public class Demo7_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) {    // 如果报运行异常,编译时不处理,在上层方法上不用声明
        if (age > 0 && age < 150) {
            this.age = age;
        } else {
            //throw new RuntimeException("年龄非法"); // 运行时异常可以不抛出
            // Exception e = new Exception("年龄非法");
            throw new AgeOutOfBoundsException("年龄非法");
        }
    }

}

class AgeOutOfBoundsException extends RuntimeException{
    public AgeOutOfBoundsException() {
        super();
        
    }
    public AgeOutOfBoundsException(String message) {
        super(message);
        
    }    
}
throws

 

throw的概述和throws的区别

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

* B:案例分析
  * 分别演示编译时异常对象和运行时异常对象的抛出

* C:throw 和 throws 的区别
  * a:throws
    * 用在方法声明后面,跟的是异常类名
    * 可以跟多个异常类名,用逗号隔开
    * 表示抛出异常,由该方法的调用者来处理

  * b:throw
    * 用在方法体内,跟的是异常对象名
    * 只能抛出一个异常对象名
    * 表示抛出异常,由方法体内的语句处理

 

finally关键字的特点及作用

* A:finally的特点
  * 被 finally控制的语句体一定会执行
  * 特殊情况:在执行到 finally之前JVM以退出( 比如System.exit(0) )

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

* C:案例演示
  * finally 关键字的特点及作用

package com.heima.exception;

public class Demo7_Final {
    /*
     * return语句相当于方法的最后一口气
     * 在它将死之前,会看一看有没有final类,帮其完成遗愿
     * 如果有,就将final类执行,后再彻底返回
     */
    public static void main(String[] args) {
        try {
            System.out.println( 1 / 0);
        } catch (Exception e) {
            System.out.println("除数为0了");
            // System.exit(0);    // 退出JVM虚拟机
            // return; // 即使有return也会执行 finally
        } finally {
            // 一般用于释放资源,关闭IO流
            System.out.println("看看我执行了吗");
        }
        System.out.println("--------------");
    }
}
finally

 

finally关键字的区别

* A:面试题1
  * final,finally和 finalize的区别

* B:面试题2
  * 如果catch里面有return语句,请问finally的代码还会执行吗?如果会,请问实在 return前还是 return后

package com.heima.test;

public class Test1 {
    /*
    面试题A:
     * final 可以修饰类,不能被继承
     *            可以修饰方法,不能被重写
     *            可以修饰变量,只能赋值一次
     * 
     * finally 是try语句内的一个语句体,不能单独使用,一般用来释放资源
     * 
     *     finalize 是一个方法,当垃圾回收器确定不存在对该对象的更多引用时,会由对象的垃圾回收器调用此方法 
     */
    public static void main(String[] args) {
        Demo demo = new Demo();
        System.out.println(demo.method());    // 30
    }
}

class Demo {
    public int method() {
        int x = 10;
        try {
            x = 20;
            System.out.println(1 / 0);
            return x;
        } catch (Exception  e) {
            x = 30;
            return x;    // 先将要return的内容打包, 再执行 finally
        } finally {
            x = 40;    // finally内写赋值语句没有意义
            // return x; // 千万不要在finally里面写返回语句,因为finally的作用是释放资源,是肯定会执行的,
                        // 如果在这里面写返回语句,那么try和catch的结果都会被改变,所以这么写就是犯罪
        }
    }
}
Test1

 

自定义异常概述和基本使用

* A:为什么需要自定义异常
  * 通过名字区分到底是什么异常,使程序员有针对的解决办法
  * 举例:人的年龄

* B:自定义异常概述
  * 继承自Exception
  * 继承自RuntimeException

* C:案例演示
  * 自定义异常的基本使用

package com.heima.exception;

public class Demo8_Exception {
    // 自定义异常的作用只在于区分不同异常的名字
    public static void main(String[] args) {
        
    }
}

class AgeOutOfBoundsException1 extends RuntimeException{
    public AgeOutOfBoundsException1() {
        super();
    }
    
    public AgeOutOfBoundsException1(String message) {
        super(message); // 调用父类构造
    }    
}
Exception

 

异常的注意事项及如何使用异常处理

* A:异常的注意事项
  * a:子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类(父亲坏了,儿子不能比父亲更坏)
  * b:如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或是它的子集,子类不能抛出父类没有的异常
  * c:如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能 try,不能 throw

* B:如何处理异常
  * 原则:如果该功能内部可以将问题处理,用try,如果处理不了,用throw交由调用者处理。
  * 区别:
    * 后续程序需要继续执行就用try
    * 后续不需要执行就用throw

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

异常练习

* 键盘录入一个 int类型,对其求二进制的表现形式
  * 如果录入的整数过大,给予提示  -》录入的整数过大,请重新录入一个整数
  * 如果录入的是小数,给予提示 -》录入的是小数,请重新录入
  * 如果录入的是其他字符,给予提示 -》录入的是非法字符,请重新录入

package com.heima.test;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner;

public class Test2 {
    /*
     * 分析: 
     * 1、创建键盘录入对象 
     * 2、将键盘录入的结果存储在String类型的字符串中因为如果存储int类型,
     *         其中存在不符合条件的数值的话,就会直接报错,无法进行后续判断 
     * 3、键盘录入的结果转换程int类型的数据,是正确的还是错误的
     * 4、正确的直接转换,错误的进行判断
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // 创建键盘录入对象
        
        while (true) {
            System.out.println("请输入一个整数:"); // 提示键盘录入
            String line = sc.nextLine(); // 将键盘录入的结果存储在line中
            try {
                int i = Integer.parseInt(line); // 将字符串转换为整数
                System.out.println(Integer.toBinaryString(i)); // 转换为二进制型字符串
                break; // 跳出循环
            } catch (NumberFormatException exception) {
                try {
                    new BigInteger(line); // 判断是否为过大的整数
                    System.out.println("录入数据过大");
                } catch (Exception e) {    // alt + shift + z (try catch 快捷键)
                    try {
                        new BigDecimal(line); // 判断是否为小数
                        System.out.println("录入了小数");
                    } catch (Exception e1) {
                        System.out.println("录入非法整数");
                    }
                }
            }
        }

    }
}
Test2

 

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 类的构造方法

package com.heima.file;

import java.io.File;

public class Demo1_File {

    public static void main(String[] args) {
        // demo1();
        // demo2();
        // demo3();
    }

    public static void demo3() {
        File parent = new File("D:\\PanDownload\\java\\"
                + "01、第一阶段java基础(更多视频教程 www.pcsky.wang)"
                + "\\day19\\day19\\video");
        String child = "001_今日内容.avi";
        File file = new File(parent, child);
        System.out.println(parent.exists());
        System.out.println(file.exists());
    }

    public static void demo2() {
        String parent = "D:\\PanDownload\\java\\" // 父级路径
                + "01、第一阶段java基础(更多视频教程 www.pcsky.wang)"
                + "\\day19\\day19\\video";
        String child = "001_今日内容.avi"; // 子级路径
        File file = new File(parent, child); // 将一个地址定义到两个路径中,提高了它的灵活性
        System.out.println(file.exists());
    }

    public static void demo1() {
        File file = new File("D:\\PanDownload\\java\\"
                + "01、第一阶段java基础(更多视频教程 www.pcsky.wang)"
                + "\\day19\\day19\\video\\001_今日内容.avi"); // 一个\表示转义符,两个\\才表示路径分隔符
        System.out.println(file.exists()); // 判断文件是否存在
        
        File file2 = new File("xxx.txt"); // 相对路径
        System.out.println(file2.exists());
        
        File file3 = new File("yyy.txt");
        System.out.println(file3.exists());
    }
}
File 

 

File类的创建功能

* A:创建功能
  * public boolean creatNewFile() :创建文件,如果存在这样的文件,就不创建了
  * public boolean mkdir() :创建文件夹,如果存在这样的文件夹,就不创建了
  * public boolean mkdirs() :递归地创建文件夹

* B:案例演示
  * File类的创建功能

  * 注意事项:
    * 如果你创建文件或者文件夹忘了写盘符路径,那么默认在当前项目的路径下

package com.heima.file;

import java.io.File;
import java.io.IOException;

public class Demo2_FileMethod {

    public static void main(String[] args) throws IOException {
        // demo1();
        // demo2();
    }

    public static void demo2() {
        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("ccc\\ddd");
        System.out.println(dir3.mkdirs()); // 创建多级文件夹
    }

    public static void demo1() throws IOException {
        File file = new File("yyy.txt");
        System.out.println(file.createNewFile()); // 如果没有就创建,返回true;如果有就不创建,返回false

        File file2 = new File("zzz");
        System.out.println(file2.createNewFile());
    }
}
File

 

File类的重命名和删除功能

* A:重命名和删除功能
  * public boolean renameTo(File dest) :把文件重命名为指定的文件路径
  * public boolean delete() :删除文件或者文件夹

* B:重命名注意事项
  * 如果路径名相同,就是改名
  * 如果路径名不同,就是移动

* C:删除注意事项
  * Java中的删除不走回收站
  * 要删除一个文件夹,请注意该文件夹内不能包含文件或文件夹

package com.heima.file;

import java.io.File;
import java.io.IOException;

public class Demo3_FileMethod {

    public static void main(String[] args) throws IOException {
        // demo1();
        // demo2();
    }

    public static void demo2() {
        File file1 = new File("yyy.txt");
        System.out.println(file1.delete());    // java中删除不走回收站,因此删除时要小心
        
        File file2 = new File("ccc");    // 只能删除空的文件夹
        System.out.println(file2.delete());
    }

    public static void demo1() throws IOException {
        File file1 = new File("xxx.txt");
        File file2 = new File("aaa\\ooo.txt");
        
        System.out.println(file1.createNewFile());
        System.out.println(file1.renameTo(file2));
    }
}
File

 

File类的判断功能

* A:判断功能
  * public boolean isDirectory() :判断是否是目录
  * public boolean isFile() :判断是否是文件
  * public boolean exists :判断文件是否存在
  * public boolean canRead() :判断文件是否可读
  * public boolean canWrite() :判断文件是否可写
  * public boolean isHidden() :判断文件是否被隐藏了

* B:案例演示
  * File类的判断功能

package com.heima.file;

import java.io.File;

public class Demo4_FileMethod {

    public static void main(String[] args) {
        // demo1();
        // demo2();
    }

    public static void demo2() {
        File file = new File("zzz");
        file.setReadable(false); // 设置读取的权限
        System.out.println(file.canRead()); // Windows系统认为所有的文件都是可读的
        file.setWritable(false); // 设置可写的权限
        System.out.println(file.canWrite()); // Windows系统可以设置为不可写

        File file2 = new File("aaa.txt");
        System.out.println(file2.isHidden());    // 判断是否是隐藏的
    }

    public static void demo1() {
        File dir1 = new File("aaa"); // 文件夹
        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());
    }
}
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类的获取功能

package com.heima.file;

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

public class Demo5_FileMethod {

    public static void main(String[] args) {
        // demo1();
        // demo2();
        
    }

    public static void demo2() {
        File dir = new File("F:\\eclipse\\day19");
        String[] arr = dir.list();    // 仅仅获取文件名
        System.out.println(Arrays.toString(arr));
        
        File[] subFiles = dir.listFiles();    // 获取文件对象,全路径,可以直接操作
        for (File file : subFiles) {
            System.out.println(file);
        }
    }

    public static void demo1() {
        File file1 = new File("ccc.txt");
        File file2 = new File("F:\\eclipse\\day19\\ccc.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(file1.lastModified());// 获取最后一次修改文件的时间,毫秒值
        Date d = new Date(file1.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        System.out.println(sdf.format(d));
    }
}
File

 

输出指定目录下指定后缀的文件名

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

package com.heima.test;

import java.io.File;

public class Test3 {

    public static void main(String[] args) {
        File dir = new File("F:\\一寸照");
        
        /*String[] arr = dir.list();    // 获取该目录下所有文件或文件夹
        for (String string : arr) {
            if (string.endsWith(".jpg")) { // 判断文件是否以.jpg结尾
                System.out.println(string);
            }
        }*/
        
        File[] subFiles = dir.listFiles();    // 获取该目录下所有的文件或文件夹对象
        for (File subFile : subFiles) {
            if (subFile.isFile() && subFile.getName().endsWith(".jpg")) {
                System.out.println(subFile);
            }
        }
    }
}
Test3 

 

文件名过滤器的概述及使用

* A:文件名称过滤器的概述
  * public String[ ] list(FilenameFilter fileter)
  * public File[ ] listFiles(FileFilter filter)

* B:文件名称过滤器的使用
  * 需求:判断E盘目录下是否有后缀名为.jpg的文件,如果有就输出

* C:源码分析
  * 带文件名称的过滤器的 list() 方法的源码

package com.heima.file;

import java.io.File;
import java.io.FilenameFilter;

public class Demo6_FileMethod {

    public static void main(String[] args) {
        File dir = new File("F:\\一寸照");
        String[] arr = dir.list(new FilenameFilter() {    // 创建过滤器,数组内全是返回值为true的

            @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);
        }
    }
}
File
    public String[] list(FilenameFilter filter) {
        String names[] = list();
        if ((names == null) || (filter == null)) {
            return names;
        }
        List<String> v = new ArrayList<>();
        for (int i = 0 ; i < names.length ; i++) {
            if (filter.accept(this, names[i])) {
                v.add(names[i]);
            }
        }
        return v.toArray(new String[v.size()]);
    }
FileFilter源码

 

posted @ 2020-04-15 15:59  小么VinVin  阅读(150)  评论(0编辑  收藏  举报