您的位置:首页 > 职场人生

黑马程序员_java语言_异常类和File类的分析

2015-06-03 20:03 465 查看
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流!
----------

###12.01_异常(异常的概述和分类)
* A:异常的概述

    * 异常就是Java程序在运行过程中出现的错误。
* B:异常的分类

    * 通过API查看Throwable

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

    * Exception

        程序运行时或者编译期产生的异常,都可以叫做Exception,包括运行期异常和编译器异常

C:异常的继承体系

    * Throwable
        * Error    
        * Exception
            * RuntimeException

Throwable 类是 Java 语言中所有错误或异常的超类

 * throwable的分类

 *   |- Error 错误

 *     OutOfMemoryError 内存溢出

 *     StackOverflowError 栈溢出

 *   |- Exception 异常

 *      编译期异常: 在代码编写好后,编译的时候产生的异常

 *          ParseException 解析异常

 *     运行期异常: 代码编译的时候没出错,运行的时候出现了异常

 *          ConcurrentModificationException 并发修改异常

 *          NullPointerException 空指针异常

 *          ArrayIndexOutOfBoundsException 数组角标越界异常

            StringIndexOutOfBoundsException 字符串角标越界异常

     

 异常: 就是程序在运行的时候,出现的错误,我们用代码演示一下:

<span style="font-size:14px;">		//编译期异常
//		String time = "2015-05-13";
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
//		Date date = sdf.parse(time);
//		System.out.println(date);

//运行期异常
int[] arr = {1,2,3};
arr = null;
System.out.println(arr[0]);</span>

###12.02_异常(JVM默认是如何处理异常的)
* A:JVM默认是如何处理异常的

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

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

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

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

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

    * JVM默认如何处理异常

      当出现了异常后,JVM直接退出结束程序,后面的代码不执行

 *    1:显示出异常类的名字

 *    2:显示出了异常的错误位置

 *    3:异常信息

<span style="font-size:14px;">public class ExceptionDemo {
public static void main(String[] args) {

//int[] arr = {1,2,3};
//arr = null;
//System.out.println(arr[1]);//NullPointerException

System.out.println(3/0);//ArithmeticException 算术异常

System.out.println("哈哈");
}
}
</span>

###12.03_异常(try...catch的方式处理异常1)
* A:异常处理的两种方式

    * a:try…catch…finally

    * b:throws

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

    * try…catch…finally
* C:案例演示

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

<span style="font-size:14px;">   int x = 3;
int y = 0;
try{
//可能产生异常的代码
System.out.println(x/y);
} catch (ArithmeticException e) {
//解决异常的代码
System.out.println("赶快去解决, 解决好了,回来上课");
}
System.out.println("继续听课");</span>


###12.04_异常(try...catch的方式处理异常2)
* A:案例演示

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

    同一时刻,只能处理一个异常

 *     每个异常的处理方式可以不同

 *   jdk7的新的异常处理方式(平级异常),所有的异常 一起处理, 并且处理的方式也是相同的

 *    格式:

 *     try{

 *      可能出现异常的代码

 *     } catch (异常类名1 | 异常类名2 | ... 异常对象名) {

 *      异常处理方式

 *     }

<span style="font-size:14px;">                int x = 3;
int y = 1;//0;
int[] arr = new int[0];

try {
System.out.println(x/y);//ArithmeticException: / by zero
System.out.println(arr[0]);//ArrayIndexOutOfBoundsException: 0
} catch(ArithmeticException e) {
System.out.println("除数不能为0");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("角标越界异常");
}

System.out.println("结束了");

}
</span>

###12.05_异常(编译期异常和运行期异常的区别)
* A:编译期异常和运行期异常的区别

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

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

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

    * 运行时异常
        * 无需显示处理,也可以和编译时异常一样处理
###12.06_异常(Throwable的几个常见方法)
* A:Throwable的几个常见方法

    * a:getMessage()
        * 获取异常信息,返回字符串。

    * b:toString()
        * 获取异常类名和异常信息,返回字符串。

    * c:printStackTrace()
        * 获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。
* B:案例演示

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

<span style="font-size:14px;">private static void method() throws ParseException {
String time = "2015-05-13";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
Date date = sdf.parse(time);
System.out.println(date);
}</span>

###12.07_异常(throws的方式处理异常)
* A:throws的方式处理异常

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

    * 那么就通过throws在方法上标识。
* B:案例演示

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

<span style="font-size:14px;">private static void method(int x, int y) throws ParseException, NullPointerException {

if (y == 0) {
//给出一个算术异常对象,并抛出去,让别人处理该异常
//throw new ArithmeticException(); 运行期异常
throw new ParseException("haha", 0);

} else {
System.out.println(x/y);
}
</span>

###12,08_异常(throw的概述以及和throws的区别)
* A:throw的概述

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

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

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

###12.09_异常(finally关键字的特点及作用)
* A:finally的特点

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

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

    * 用于释
d396
放资源,在IO流操作和数据库操作中会见到
* C:案例演示

    * finally关键字的特点及作用

<span style="font-size:14px;">public class ExceptionDemo {
public static void main(String[] args) {
int x=10;
int y=0;
try{
System.out.println(x/y);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
System.out.println("用手纸解决一下");
}

System.out.println("从WC出来了");
}
}
</span>


###12.10_异常(finally关键字的面试题)
* A:面试题1

    * final,finally和finalize的区别

       final用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。

    
finally表示异常处理语句,它里面的语句不管是否有异常都回执行

       finalize是Object类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法,可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等
* B:面试题2

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

      会,在return语句执行的中间运行的finally语句
    
###12.11_异常(异常的注意事项及如何使用异常处理)
* A:异常注意事项

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

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

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

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

    * 区别:
        * 后续程序需要继续运行就try
        * 后续程序不需要继续运行就throws
        

    * 如果JDK没有提供对应的异常,需要自定义异常。
###12.12_异常(练习)

 

<span style="font-size:14px;">/*
* try...catch...finally
* throws
* throw
*
* try : 里面的内容是表示可能出现异常的代码
* catch: 解决异常问题
* finally: try..catch语句中 必须要执行的操作, 注意:如果在finally执行前,JVM前退出,finally不执行
* throws: 把可能发生的异常,抛出去,让调用者来处理异常
* throw: 抛出一个 *
*/
public class ExceptionDemo {
public static void main(String[] args) {

//method(3, 1);
try {
method(3, 0);
} catch (ParseException e) {
e.printStackTrace();
}
}

private static void method(int x, int y) throws ParseException, NullPointerException {

if (y == 0) {
//给出一个算术异常对象,并抛出去,让别人处理该异常
//throw new ArithmeticException(); 运行期异常
throw new ParseException("haha", 0);

} else {
System.out.println(x/y);
}

}
}
</span>


###12.13_File类(File类的概述和构造方法)
* A:File类的概述

    * File更应该叫做一个路径
        * 文件路径或者文件夹路径  
        * 路径分为绝对路径和相对路径
        * 绝对路径是一个固定的路径,从盘符开始
        * 相对路径相对于某个位置,在eclipse下是指当前项目下,在dos下指的是当前路径

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

  首先我们对于IO做一个简单的图解:


* B:构造方法

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

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

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

    * File类的构造方法

<span style="font-size:14px;">                 //方式1
//File file = new File("E:\\itcast\\20150412\\联系方式.txt");
//方式2
//File file = new File("E:\\itcast\\20150412","联系方式.txt");
//方式3
File parent = new File ("E:\\itcast\\20150412");
File file = new File(parent, "联系方式.txt");
</span>

###12.14_File类(File类的创建功能)
* A:创建功能

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

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

    * public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来
* B:案例演示

    * File类的创建功能

<span style="font-size:14px;">                //创建文件对象
File file = new File("E:\\test\\abc.txt");
//把file对象代表的文件创建出来
boolean flag = file.createNewFile();
System.out.println(flag);

//System.out.println(file);
//--------------------------------
//创建文件对象
File path = new File("E:\\test\\aaa");
//把path对象代表的文件夹创建对象
flag = path.mkdir();
System.out.println(flag);

//----------------------------
//创建文件对象
File path2 = new File("E:\\test\\a\\b\\c\\d");
//把path对象代表的文件夹创建对象
flag = path2.mkdirs();
System.out.println(flag);

//-------------------------------
//创建一个文件,不小心,忘记写盘符了
File path3 = new File("haha.txt");
flag = path3.createNewFile();
System.out.println(flag);
</span>

 * 注意事项:
        * 如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。
        
###12.15_File类(File类的删除功能)
* A:删除功能

    * public boolean delete():删除文件或者文件夹
* B:案例演示

    * File类的删除功能

<span style="font-size:14px;">             /创建FIle对象
//删除文件
File file = new File("E:\\test\\abc.txt");
boolean flag = file.delete();
System.out.println(flag);

//删除文件夹
//删除aaa文件夹
file = new File("E:\\test\\aaa");
flag = file.delete();
System.out.println(flag);

//删除a文件夹
file = new File("E:\\test\\a");
flag = file.delete();
System.out.println(flag);</span>

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

###12.16_File类(File类的重命名功能)
* A:重命名功能

     public boolean renameTo(File dest)重新命名此抽象路径名表示的文件

 *    把当前File对象的名称 改为 指定的File对象的名称

 * 

    注意:renameTo方法

 *    如果 两个File对象,在同一个文件夹中,该功能是 重命名功能

 *    如果两个File对象,不在同一个文件夹中,该功能是 剪切 + 重命名功能

  案例演示:

<span style="font-size:14px;">public class FileMethodDemo5 {
public static void main(String[] args) {
//原名
File file = new File("E:\\test\\abc.txt");
//新名
//File newFile = new File("E:\\test\\newabc.txt");
File newFile = new File("D:\\newabc.txt");
//重命名
boolean flag = file.renameTo(newFile);
System.out.println(flag);
}
}
</span>

###12.17_File类(File类的判断功能)
* A:判断功能

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

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

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

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

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

    * public boolean isHidden():判断是否隐藏
* B:案例演示

    * File类的判断功能

<span style="font-size:14px;">                //创建File对象
File file = new File("E:\\test\\abc.txt");

System.out.println("canRead:" + file.canRead());
System.out.println("canWrite:" + file.canWrite());
System.out.println("exists:" + file.exists());
System.out.println("isAbsolute:" + file.isAbsolute());
System.out.println("isDirectory:" + file.isDirectory());
System.out.println("isFile:" + file.isFile());
System.out.println("isHidden:" + file.isHidden());</span>

###12.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类的获取功能

<span style="font-size:14px;">                File file = new File("aaa\\haha.txt");
System.out.println("getAbsolutePath:" + file.getAbsolutePath());
System.out.println("getName:" + file.getName());
System.out.println("getPath:" + file.getPath());
long time = file.lastModified();
Date date = new Date(time);
System.out.println("lastModified:" + date);

System.out.println("length:" + file.length());

//返回当前电脑上所有的盘符信息
File[] roots = File.listRoots();
for (File f : roots) {
System.out.println(f);
}
file = new File("E:\\resource副本");
//返回当前File所代表的目录中,所有的文件和文件夹的String对象
String[] strs = file.list();
for (String str : strs) {
System.out.println(str);
}
//返回当前File所代表的目录中,所有的文件和文件夹的File对象
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);
}</span>

###12.19_File类(文件名称过滤器的概述及使用)
* A:文件名称过滤器的概述

    * public String[] list(FilenameFilter filter)

    * public File[] listFiles(FilenameFilter filter)
* B:文件名称过滤器的使用

    * 需求:判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
###12.20_File类(练习)

* 练习: 把指定文件夹中的文件名称,统一改名

    分析:

    1: 获取指定文件夹下 所有的File对象

 *  2:获取到每一个File对象

 *  3:准备好新文件的名称

 *    a:获取到原文件的名字

 *    b:获取位置 "]"

 *    c:截取字符串 位置+1 开始截取到末尾

 *    d:拼接新文件的File对象

 *  4:重命名,

<span style="font-size:14px;">public class FileTest {
public static void main(String[] args) {
File file = new File("E:\\各种专治");
//1: 获取指定文件夹下 所有的File对象
File[] files = file.listFiles();
//2:获取到每一个File对象
for (File src : files) {
//3:准备好新文件的名称
//a:获取到原文件的名字
String name = src.getName();//[www-itcast-cn]专治各种疼痛02.mp4
//b:获取位置 "]"
int index = name.indexOf("]");
//c:截取字符串 位置+1 开始截取到末尾
String newName = name.substring(index+1);//专治各种疼痛02.mp4
//d:拼接新文件的File对象
File dest = new File(file, newName);

//4:重命名
src.renameTo(dest);
}
}
}
</span>


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: