Java笔记

No_16_0319 Java基础学习第二十天

2016-03-21  本文已影响52人  lutianfei
文档版本 开发工具 测试平台 工程名字 日期 作者 备注
V1.0 2016.03.19 lutianfei none

[TOC]


异常

异常分类

骑车去旅行:
  Error:走到半路上,发生山路塌陷,或者出现了泥石流,这个问题很严重,不是班长能够立马解决的。
  Exception:出门前,班长要看看车轮子以及车链子等是否还在
  RuntimeException:在骑车的过程中,有好路不走,偏偏要走石子路

异常处理方案

try…catch处理方式

一个异常的情况
public class ExceptionDemo {
    public static void main(String[] args) {
        // 第一阶段
        int a = 10;
        // int b = 2;
        int b = 0;

        try {
            System.out.println(a / b);
        } catch (ArithmeticException ae) {
            System.out.println("除数不能为0");
        }

        // 第二阶段
        System.out.println("over");
    }
}
多个异常的情况
public class ExceptionDemo2 {
    public static void main(String[] args) {
        method4();
    }

    public static void method4() {
        int a = 10;
        int b = 0;
        int[] arr = { 1, 2, 3 };

        // 爷爷在最后
        try {
            System.out.println(a / b);
            System.out.println(arr[3]);
            System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("你访问了不该的访问的索引");
        } catch (Exception e) {
            System.out.println("出问题了");
        }

        // 爷爷在前面是不可以的
        // try {
        // System.out.println(a / b);
        // System.out.println(arr[3]);
        // System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
        // } catch (Exception e) {
        // System.out.println("出问题了");
        // } catch (ArithmeticException e) {
        // System.out.println("除数不能为0");
        // } catch (ArrayIndexOutOfBoundsException e) {
        // System.out.println("你访问了不该的访问的索引");
        // }

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

    // 两个异常
    public static void method2() {
        int a = 10;
        int b = 0;
        try {
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        }

        int[] arr = { 1, 2, 3 };
        try {
            System.out.println(arr[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("你访问了不该的访问的索引");
        }

        System.out.println("over");
    }
JDK7 新特性
public class ExceptionDemo3 {
    public static void main(String[] args) {
        method();
    }

    public static void method() {
        int a = 10;
        int b = 0;
        int[] arr = { 1, 2, 3 };

        // JDK7的处理方案
        try {
            System.out.println(a / b);
            System.out.println(arr[3]);
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println("出问题了");
        }

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

}
编译时异常运行时异常的区别
public class ExceptionDemo {
    public static void main(String[] args) {
        // int a = 10;
        // int b = 0;
        // if (b != 0) {
        //运行期异常
        // System.out.println(a / b);
        // }

        String s = "2014-11-20";
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // Date d = sdf.parse(s);
        
        //编译期异常
        try {
            Date d = sdf.parse(s);
            System.out.println(d);
        } catch (ParseException e) {
            // e.printStackTrace();
            System.out.println("解析日期出问题了");
        }
    }
}

Throwable中的方法

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * 在try里面发现问题后,jvm会帮我们生成一个异常对象,然后把这个对象抛出,和catch里面的类进行匹配。
 * 如果该对象是某个类型的,就会执行该catch里面的处理信息。
 */
public class ExceptionDemo {
    public static void main(String[] args) {
        String s = "2014-11-20";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d = sdf.parse(s); // 创建了一个ParseException对象,然后抛出去,和catch里面进行匹配
            System.out.println(d);
        } catch (ParseException e) { // ParseException e = new ParseException();
            // ParseException
            // e.printStackTrace();

            // getMessage()
            // System.out.println(e.getMessage());
            // Unparseable date: "2014-11-20"

            // toString()
            // System.out.println(e.toString());
            // java.text.ParseException: Unparseable date: "2014-11-20"
            
            e.printStackTrace();
            //跳转到某个指定的页面(index.html)
        }
        
        System.out.println("over");
    }
}
throws
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * 有些时候,我们是可以对异常进行处理的,但是又有些时候,我们根本就没有权限去处理某个异常。
 * 或者说,我处理不了,我就不处理了。
 * 为了解决出错问题,Java针对这种情况,就提供了另一种处理方案:抛出。
 */
public class ExceptionDemo {
    public static void main(String[] args) {
        System.out.println("今天天气很好");
        try {
            method();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("但是就是不该有雾霾");

        method2();
    }

    // 运行期异常的抛出
    public static void method2() throws ArithmeticException {
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }

    // 编译期异常的抛出
    // 在方法声明上抛出,是为了告诉调用者,你注意了,我有问题。
    public static void method() throws ParseException {
        String s = "2014-11-20";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(s);
        System.out.println(d);
    }
}
throws和throw的区别
public class ExceptionDemo {
    public static void main(String[] args) {
        // method();

        try {
            method2();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void method() {
        int a = 10;
        int b = 0;
        if (b == 0) {
            throw new ArithmeticException();
        } else {
            System.out.println(a / b);
        }
    }

    public static void method2() throws Exception {
        int a = 10;
        int b = 0;
        if (b == 0) {
            throw new Exception();
        } else {
            System.out.println(a / b);
        }
    }
}

如何处理异常

finally的特点作用及面试题

public class FinallyDemo2 {
    public static void main(String[] args) {
        System.out.println(getInt());
    }

    public static int getInt() {
        int a = 10;
        try {
            System.out.println(a / 0);
            a = 20;
        } catch (ArithmeticException e) {
            a = 30;
            return a;
            /*
             * return a在程序执行到这一步的时候,这里不是return a而是return 30;这个返回路径就形成了。
             * 但是呢,它发现后面还有finally,所以继续执行finally的内容,a=40
             * 再次回到以前的返回路径,继续走return 30;
             */
        } finally {
            a = 40;
        //  return a;//如果这样结果就是40了。
        }
         return a;
    }
}

try...catch...finally的格式变形

自定义异常

public class MyException extends Exception {
    public MyException() {
    }

    public MyException(String message) {
        super(message);
    }
}

// public class MyException extends RuntimeException {
//
// }




public class Teacher {
    public void check(int score) throws MyException {
        if (score > 100 || score < 0) {
            throw new MyException("分数必须在0-100之间");
        } else {
            System.out.println("分数没有问题");
        }
    }

    // 针对MyException继承自RuntimeException
    // public void check(int score) {
    // if (score > 100 || score < 0) {
    // throw new MyException();
    // } else {
    // System.out.println("分数没有问题");
    // }
    // }
}




/*
 * 自定义异常测试类
 */
public class StudentDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生成绩:");
        int score = sc.nextInt();

        Teacher t = new Teacher();
        try {
            t.check(score);
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}

异常注意事项

public class ExceptionDemo {

}

class Fu {
    public void show() throws Exception {
    }

    public void method() {
    }
}

class Zi extends Fu {
    @Override
    public void show() throws ArithmeticException {

    }

    @Override
    public void method() {
         String s = "2014-11-20";
         SimpleDateFormat sdf = new SimpleDateFormat();
         Date d = sdf.parse(s);
         System.out.println(d);
    }
}

File类

File类的概述

构造方法

public class FileDemo {
    public static void main(String[] args) {
        // File(String pathname):根据一个路径得到File对象
        // 把e:\\demo\\a.txt封装成一个File对象
        File file = new File("E:\\demo\\a.txt");

        // File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
        File file2 = new File("E:\\demo", "a.txt");

        // File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
        File file3 = new File("e:\\demo");
        File file4 = new File(file3, "a.txt");

        // 以上三种方式其实效果一样
    }
}

File类的成员方法

public class FileDemo {
    public static void main(String[] args) throws IOException {
        // 需求:我要在e盘目录下创建一个文件夹demo
        File file = new File("e:\\demo");
        System.out.println("mkdir:" + file.mkdir());

        // 需求:我要在e盘目录demo下创建一个文件a.txt
        File file2 = new File("e:\\demo\\a.txt");
        System.out.println("createNewFile:" + file2.createNewFile());

        // 需求:我要在e盘目录test下创建一个文件b.txt
        // Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
        // 注意:要想在某个目录下创建内容,该目录首先必须存在。
        // File file3 = new File("e:\\test\\b.txt");
        // System.out.println("createNewFile:" + file3.createNewFile());

        File file7 = new File("e:\\aaa\\bbb\\ccc\\ddd");
        System.out.println("mkdirs:" + file7.mkdirs());

        // 看下面的这个东西:
        File file8 = new File("e:\\liuyi\\a.txt");
        System.out.println("mkdirs:" + file8.mkdirs());
    }
}
/*
 * 删除功能:public boolean delete()
 */
public class FileDemo {
    public static void main(String[] args) throws IOException {
        // 创建文件
        // File file = new File("e:\\a.txt");
        // System.out.println("createNewFile:" + file.createNewFile());

        // 我不小心写成这个样子了
        File file = new File("a.txt");
        System.out.println("createNewFile:" + file.createNewFile());

        File file2 = new File("aaa\\bbb\\ccc");
        System.out.println("mkdirs:" + file2.mkdirs());

        // 删除功能:我要删除a.txt这个文件
        File file3 = new File("a.txt");
        System.out.println("delete:" + file3.delete());

        // 删除功能:我要删除ccc这个文件夹
        File file4 = new File("aaa\\bbb\\ccc");
        System.out.println("delete:" + file4.delete());

        // 删除功能:我要删除aaa文件夹
        File file6 = new File("aaa\\bbb");
        File file7 = new File("aaa");
        System.out.println("delete:" + file6.delete());
        System.out.println("delete:" + file7.delete());
    }
}
public class FileDemo {
    public static void main(String[] args) {
        // 创建一个文件对象
        // File file = new File("林青霞.jpg");

        // // 需求:我要修改这个文件的名称为"东方不败.jpg"
        // File newFile = new File("东方不败.jpg");
        // System.out.println("renameTo:" + file.renameTo(newFile));
        
        //绝对路径改名
        File file2 = new File("东方不败.jpg");
        File newFile2 = new File("e:\\林青霞.jpg");
        System.out.println("renameTo:" + file2.renameTo(newFile2));
    }
}
public class FileDemo {
    public static void main(String[] args) {
        // 创建文件对象
        File file = new File("a.txt");

        System.out.println("isDirectory:" + file.isDirectory());// false
        System.out.println("isFile:" + file.isFile());// true
        System.out.println("exists:" + file.exists());// true
        System.out.println("canRead:" + file.canRead());// true
        System.out.println("canWrite:" + file.canWrite());// true
        System.out.println("isHidden:" + file.isHidden());// false
    }
}
public class FileDemo {
    public static void main(String[] args) {
        // 创建文件对象
        File file = new File("demo\\test.txt");

        System.out.println("getAbsolutePath:" + file.getAbsolutePath());
        System.out.println("getPath:" + file.getPath());
        System.out.println("getName:" + file.getName());
        System.out.println("length:" + file.length());
        System.out.println("lastModified:" + file.lastModified());

        // 1416471971031
        Date d = new Date(1416471971031L);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = sdf.format(d);
        System.out.println(s);
    }
}
public class FileDemo {
    public static void main(String[] args) {
        // 指定一个目录
        File file = new File("e:\\");

        // public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
        String[] strArray = file.list();
        for (String s : strArray) {
            System.out.println(s);
        }
        System.out.println("------------");

        // public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
        File[] fileArray = file.listFiles();
        for (File f : fileArray) {
            System.out.println(f.getName());
        }
    }
}

File类练习

/*
 * 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 * 
 * 分析:
 *      A:封装e判断目录
 *      B:获取该目录下所有文件或者文件夹的File数组
 *      C:遍历该File数组,得到每一个File对象,然后判断
 *      D:是否是文件
 *          是:继续判断是否以.jpg结尾
 *              是:就输出该文件名称
 *              否:不搭理它
 *          否:不搭理它
 */
public class FileDemo {
    public static void main(String[] args) {
        // 封装e判断目录
        File file = new File("e:\\");

        // 获取该目录下所有文件或者文件夹的File数组
        File[] fileArray = file.listFiles();

        // 遍历该File数组,得到每一个File对象,然后判断
        for (File f : fileArray) {
            // 是否是文件
            if (f.isFile()) {
                // 继续判断是否以.jpg结尾
                if (f.getName().endsWith(".jpg")) {
                    // 就输出该文件名称
                    System.out.println(f.getName());
                }
            }
        }
    }
}
/*
 * 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 * A:先获取所有的,然后遍历的时候,依次判断,如果满足条件就输出。
 * B:获取的时候就已经是满足条件的了,然后输出即可。
 * 
 * 要想实现这个效果,就必须学习一个接口:文件名称过滤器
 * public String[] list(FilenameFilter filter)
 * public File[] listFiles(FilenameFilter filter)
 */
public class FileDemo2 {
    public static void main(String[] args) {
        // 封装e判断目录
        File file = new File("e:\\");

        // 获取该目录下所有文件或者文件夹的String数组
        // public String[] list(FilenameFilter filter)
        String[] strArray = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                // return false;
                // return true;
                // 通过这个测试,我们知道,
                //这个文件或者文件夹的名称加不加到数组中,取决于这里的返回值是true还是false
                // 所以,这个的true或者false应该是我们通过某种判断得到的
                // System.out.println(dir + "---" + name);
                // File file = new File(dir, name);
                // // System.out.println(file);
                // boolean flag = file.isFile();
                // boolean flag2 = name.endsWith(".jpg");
                // return flag && flag2;
                return new File(dir, name).isFile() && name.endsWith(".jpg");
            }
        });

        // 遍历
        for (String s : strArray) {
            System.out.println(s);
        }
    }
}
/*
 * 需求:把E:\评书\三国演义下面的视频名称修改为
 *      00?_介绍.avi
 * 
 * 思路:
 *      A:封装目录
 *      B:获取该目录下所有的文件的File数组
 *      C:遍历该File数组,得到每一个File对象
 *      D:拼接一个新的名称,然后重命名即可。
 */
public class FileDemo {
    public static void main(String[] args) {
        // 封装目录
        File srcFolder = new File("E:\\评书\\三国演义");

        // 获取该目录下所有的文件的File数组
        File[] fileArray = srcFolder.listFiles();

        // 遍历该File数组,得到每一个File对象
        for (File file : fileArray) {
            // System.out.println(file);
            // E:\评书\三国演义\三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
            // 改后:E:\评书\三国演义\001_桃园三结义.avi
            String name = file.getName(); // 三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi

            int index = name.indexOf("_");
            String numberString = name.substring(index + 1, index + 4);
            // System.out.println(numberString);

            // int startIndex = name.lastIndexOf('_');
            // int endIndex = name.lastIndexOf('.');
            // String nameString = name.substring(startIndex + 1, endIndex);
            // System.out.println(nameString);
            int endIndex = name.lastIndexOf('_');
            String nameString = name.substring(endIndex);

            String newName = numberString.concat(nameString); // 001_桃园三结义.avi
            // System.out.println(newName);

            File newFile = new File(srcFolder, newName); // E:\\评书\\三国演义\\001_桃园三结义.avi

            // 重命名即可
            file.renameTo(newFile);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读