黑马程序员——Java基础---异常,IO流,File类
2015-08-11 23:32
666 查看
-----------android培训、java培训、java学习型技术博客、期待与您交流!------------
一、异常
(一)异常概述
1. 异常:异常就是Java程序在运行过程中出现的错误。
2. 异常由来:问题也是现实生活中一个具体事务,也可以通过java 的类的形式进行描述,并封装成对象。其实就是Java对不正常情况进行描述后的对象体现。
3. 我们见过的异常,角标越界异常,空指针异常
(二)异常分类图解
1. 异常继承体系
java.lang.Throwable所有异常和错误的父类
Error类继Throwable
JAVA中所有错误的父类 -- 出现非常严重问题,不修改源代码,不能运行
理解:非典,艾滋,癌
Exception类继承Throwable
JAVA中所有异常的父类 -- 出现了比较轻微的问题,处理掉问题,程序继续执行
所有子类名字,后缀都是父类名字Exception
Exception下面继续分派系
RuntimeException 以及所有子类 运行异常
不是RuntimeException 编译异常
Throwable类方法
构造方法:
空参数的构造方法,没有任何异常信息
带有1个字符串参数,传递字符串表示异常的信息
成员方法:
String toString() 返回异常信息的简短描述,获取异常类名和异常信息,返回字符串。
String getMessage() 返回异常信息的详细描述,获取异常类名和异常信息,返回字符串。
void printStackTrace() 将异常追踪到标准输出流,将异常信息直接输在控制台
2. 异常举例
除数为0
数组访问越界
(三)JVM的默认处理方案
把异常的名称,错误原因及异常出现的位置等信息输出在了控制台
程序停止执行
(四)异常处理方案
1. try…catch…finally
格式:
try{
被检测的代码
可能出现异常代码
}catch(异常类 变量){
异常处理方式(写输出语句,调用方法,写判断,循环)
}
2. throw throws
throw 关键字含义:
表明方法内部会发送什么异常
如果参数传递不合法,可能导致程序不能继续执行手动抛出异常,告诉调用者,出现问题
throw写方法里面,后面new出来的异常对象
throws关键字含义
方法声明,表示有异常,请调用者处理
throws 写在方法声明上,后面写异常类的类名
throws和throw的区别
throws
用在方法声明后面,跟的是异常类名
可以跟多个异常类名,用逗号隔开
表示抛出异常,由该方法的调用者来处理
throws表示出现异常的一种可能性,并不一定会发生这些异常
throw
用在方法体内,跟的是异常对象名
只能抛出一个异常对象名
表示抛出异常,由方法体内的语句处理
throw则是抛出了异常,执行throw则一定抛出了某种异常
(五)编译时异常和运行时异常的区别
Java中的异常被分为两大类:编译时异常和运行时异常。所有的RuntimeException类及其子类的实例被称为运行时异常,其他的异常就是编译时异常
编译时异常:Java程序必须显示处理,否则程序就会发生错误,无法通过编译
运行时异常:无需显示处理,也可以和编译时异常一样处理,不需要throws声明,也不需要调用者处理。运行时异常,在程序正常运行的时候,是不能发生的。运行时期异常是不能出现的,如果出现了,必须修改源代码。
(六)finally
1. finally的特点
finally{} 不允许自己单独出现
被finally控制的语句体一定会执行
特殊情况:在执行到finally之前jvm退出了(比如System.exit(0))
2. finally的作用
用于释放资源,在IO流操作和数据库操作中会见到
(七)自定义异常类
定义类名字后缀是Exception,继承Exception或者RuntimeException
super异常信息,传递给父类构造方法
(八)异常注意事项
1. 子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。(父亲坏了,儿子不能比父亲更坏)
2. 如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
3. 如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
(九)案例
1. 除数为0,代码演示
package exception;
public class ExceptionChuShu {
public static void main(String[] args) {
try {
// 检测异常
int result = divide(5, 0);
System.out.println(result);
} catch (Exception ex) {
// 异常的处理方式
/*
* System.out.println(ex.toString());
* System.out.println(ex.getMessage());
*/
ex.printStackTrace();
}
System.out.println("over");
}
public static int divide(int a, int b) {
return a / b;
}
}
2. 空指针和数组越界异常(多个异常的平级现象)代码演示
package exception;
/*
* try…catch 多个异常的处理
* 平级现象:
* 出现的异常类之间,没有继承关系
* NullPointerException,ArrayIndexOutOfBoundsException
* Exception
* RuntimeException
* NullPointerException
* IndexOutOfBoundsException
* ArrayIndexOutOfBoundsException
*/
public class ExceptionArray {
public static void main(String[] args) {
try{
method(0);
}catch(ArrayIndexOutOfBoundsException ex){
System.out.println("出现数组越界");
ex.printStackTrace();
}catch(NullPointerException ex){
System.out.println("出现空指针");
ex.printStackTrace();
}
System.out.println("over");
}
/*
* 定义方法,抛出2个异常
* 空指针,数组越界
*/
public static void method(int x){
if(x==0){
//出现空指针
String s = null;
System.out.println(s.startsWith(""));
}else{
//出现数组越界异常
int[] arr = new int[0];
System.out.println(arr[2]);
}
}
}
3. 数组越界和集合越界(多异常,具有继承关系)代码演示
package exception;
import java.util.ArrayList;
import java.util.List;
/*
* try…catch 多异常处理,具有继承关系
* 数组越界
* ArrayIndexOutOfBoundsException
* 集合越界
* IndexOutOfBoundsException
* ArrayIndexOutOfBoundsException 继承自IndexOutOfBoundsException
* 继承关系中,类等级越高,写后面catch
*/
public class ExceptionExtends {
public static void main(String[] args) {
try {
method(1);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("出现数组越界异常");
ex.printStackTrace();
} catch (IndexOutOfBoundsException ex) {
System.out.println("出现集合越界异常");
ex.printStackTrace();
}
}
/*
* 定义方法,抛出异常 抛出数组越界,抛出集合越界
*/
public static void method(int x) {
if (x == 0) {
// 抛数组越界异常
int[] arr = new int[0];
System.out.println(arr[-1]);
} else {
// 抛出集合越界
List<String> list = new ArrayList<String>();
System.out.println(list.get(10));
}
}
}
4. throw与throws代码演示
package exception;
/*
* throw throws的使用方式
* throw方法内部手动抛出异常
* throws 方法声明,标识方法中有异常,请调用者处理
*/
public class ThrowAndThrows {
public static void main(String[] args) {
try {
abc(10, -20);
} catch (Exception ex) {
}
}
public static int abc(int a, int b) throws Exception {
return getAvg(a, b);
}
/*
* 传递两个成绩,计算平均分 成绩必须 >= 0 如果成绩非法,不要计算了,抛出异常 编译问题,方法内部抛出了异常,自己没有处理
* 我不想处理,让调用者处理
*/
public static int getAvg(int a, int b) throws Exception {
if (a < 0 || b < 0)
// 没有必要计算,直接手动抛出异常
throw new Exception("成绩小于0");
return (a + b) / 2;
}
}
5. 编译时期异常和运行时期异常代码演示
package exception;
public class CompileAndRun {
public static void main(String[] args) {
//method();//调用者必须处理
runtime();
int[] arr = null;
int max = sort(arr);
System.out.println(max);
}
// 传递数组,排序,返回数组最后索引,最大值
public static int sort(int[] arr) {
for (int x = 0; x < arr.length; x++) {
for (int y = x + 1; y < arr.length; y++) {
}
}
return arr[arr.length - 1];
}
// 方法内部抛出的运行时期异常,方法声明上不需要写throws
// 对于调用者,不需要处理
public static void runtime() {
// 手动抛出运行时期异常
throw new RuntimeException("!!!");
}
public static void method() throws Exception {
// 手动抛出编译时期异常
throw new Exception();
}
}
6. 运行时期异常的具体作用代码演示
package exception;
public class ExceptionFunction {
public static void main(String[] args) {
double d = 0;
d = getArea(-2);
System.out.println(d);
if(d > 10){
System.out.println("面积大于10");
}
}
/*
* 定义方法,计算圆形面积
* 半径平方乘以圆周率
* 半径传递参数
*/
public static double getArea(double r){
if( r < 0)
//抛出异常,传递参数非法,后面计算没有运行的必要的
throw new RuntimeException("半径不存在");
return r*r*Math.PI;
}
}
7. 自定义异常代码演示
package exception;
/*
* 自定义异常
* 计算圆形面积
* 半径 <= 0
* 异常问题,JAVA没有封装过异常对象
*
* 自己定义异常对象
*/
class FuShuException extends Exception {
FuShuException(String s) {
super(s);
}
}
class FuShuRuntimeException extends RuntimeException {
FuShuRuntimeException(String s) {
super(s);
}
}
public class ExceptionDefine {
public static void main(String[] args) {
try {
double d = getArea(-1.2);
System.out.println(d);
} catch (FuShuException ex) {
ex.printStackTrace();
}
getAreaRuntime(4.5);
}
public static double getAreaRuntime(double r) {
if (r <= 0)
// 半径问题,无法计算,抛出异常
throw new FuShuRuntimeException("半径不存在");
return r * r * Math.PI;
}
public static double getArea(double r) throws FuShuException {
if (r <= 0)
// 半径问题,无法计算,抛出异常
throw new FuShuException("半径不存在");
return r * r * Math.PI;
}
}
4. finally,证明:finally之前try return已经执行了
package exception;
public class ExceptionFinally {
public static void main(String[] args) {
int a = method();
System.out.println(a);
}
public static int method() {
int a = 1;
try {
return a;
} catch (Exception ex) {
} finally {
a = 7654;
System.out.println(a);
}
return a;
}
}
运行结果:
二、File类
(一)File类的概述
文件和目录路径名的抽象表示形式
(二)构造方法
public File(String pathname):传递字符串路径
public File(String parent,String child):传递字符串父路径,字符串子路径
public File(File parent,String child):传递File父路径,字符串子路径
代码演示
package file;
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
method();
method1();
method2();
}
public static void method2(){
File parent=new File("F:");
//创建File对象,传递File父路径,字符串子路径
File file = new File(parent,"eclipse");
System.out.println(file);
}
public static void method1(){
//创建File对象,传递字符串父路径,字符串子路径
File file= new File("F:","eclipse");
System.out.println(file);
}
public static void method(){
//创建File类对象,传递字符串路径
File file = new File("F:\\eclipse");
System.out.println(file);
}
}
运行结果:
(三)File类的成员方法
1. 创建功能
public boolean createNewFile():创建文件,创建成功返回true
public boolean mkdir():创建单级文件夹
public boolean mkdirs():创建多级文件夹
代码演示
package file;
import java.io.*;
public class SetUpFile {
public static void main(String[] args)throws IOException {
method();
method1();
}
public static void method1(){
File file = new File("F:\\hello");
boolean b=file.mkdir();
File file1 = new File("F:\\hello\\hello");
boolean b1=file1.mkdirs();
System.out.println(b);
System.out.println(b1);
}
public static void method()throws IOException{
File file = new File("F:\\zz.txt");
boolean b=file.createNewFile();
System.out.println(b);
}
}
演示结果:
2. 删除功能
public boolean delete():删除文件,删除文件夹
package file;
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
method();
}
public static void method(){
File file = new File("F:\\zz.txt");
//调用delete删除,删除的就是File构造方法中的封装的路径
boolean b = file.delete();
System.out.println(b);
}
}
运行结果:
3. 重命名功能
public boolean renameTo(File dest)
代码演示
package file;
import java.io.*;
public class RenameFile {
public static void main(String[] args) {
File file = new File("f:\\zz");
File dest = new File("f:\\ff");
boolean b=file.renameTo(dest);
System.out.println(b);
}
}
4. 判断功能
public boolean isDirectory():判断路径是不是目录
public boolean isFile():判断File构造方法中封装的路径是不是文件
public boolean exists():判断构造方法中路径是不是存在
public boolean canRead():判断文件能不能读取
public boolean canWrite():判断文件能不能写入
public boolean isHidden():判断File构造方法中封装的文件是不是隐藏属性
代码演示
package file;
/*
* File类判断方法
*/
import java.io.*;
public class JudgeFile {
public static void main(String[] args) {
method();
method1();
method2();
method3();
method4();
method5();
}
/*
* 判断File构造方法中封装的文件是不是能读,能写
* boolean canRead() 判断文件能不能读取
* boolean canWrite() 判断文件能不能写入
*/
public static void method5(){
File file = new File("F:\\zz.txt");
//调用方法canRead() 文件能不能读取
boolean b = file.canRead();
System.out.println(b);
//调用方法canWrite() 文件能不能被写入
boolean b1= file.canWrite();
System.out.println(b1);
}
/*
* 判断,File构造方法中封装的路径是不是绝对路径
* boolean isAbsolute(),路径是绝对,返回true
*/
public static void method4(){
File file = new File("f:\\zz.txt");
//调用方法 isAbsolute()判断路径是不是绝对的
boolean b = file.isAbsolute();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的文件是不是隐藏属性
* boolean isHidden() 文件是隐藏属性,返回true
*/
public static void method3(){
File file = new File("f:\\zz.txt");
//调用方法isHidden() 判断文件是不是隐藏属性
boolean b = file.isHidden();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的路径是不是文件
* boolean isFile(),构造方法中写的是文件,返回true
*/
public static void method2(){
File file = new File("f:\\java\\jre7");
//调用方法isFile() 构造方法中是不是文件
boolean b = file.isFile();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的路径是不是文件夹,即目录
* boolean isDirectory(),构造方法中写的是目录,返回true
*/
public static void method1(){
File file = new File("f:\\java");
//调用方法isDirectory判断路径是不是目录
boolean b = file.isDirectory();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的路径是不是存在
* boolean exists() 如果存在返回true
*/
public static void method(){
File file = new File("f:\\java");
//调用方法exists,判断构造方法中路径是不是存在
boolean b = file.exists();
System.out.println(b);
}
}
5. 基本获取功能
public String getAbsolutePath()
public String getPath()
public String getName()
public long length()
public long lastModified()
代码演示
package file;
import java.io.*;
import java.text.DateFormat;
import java.util.*;
public class HuoQu {
public static void main(String[] args) {
method();
method1();
method2();
method3();
method4();
method5();
}
/*
* 获取文件最后一次修改时间毫秒值
* long lastModified()
* 获取File构造方法中封装的文件最后一次修改时间毫秒值
*/
public static void method5(){
File file = new File("F:\\java");
long l=file.lastModified();
//毫秒值--日期对象Date,Date格式化
Date date= new Date(l);
//System.out.println(date);
DateFormat dateFormat=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
String time= dateFormat.format(date);
System.out.println(time);
}
/*
* 获取文件字节长度
* long length
* 获取File构造方法中封装的文件字节数
*/
public static void method4(){
File file = new File("F:\\java");
//获取文件字节长度
long l=file.length();
System.out.println(l);
}
/*
* 获取,File构造方法中封装的路径的绝对路径
* String getAbsolutePath 返回的是String对象
* String getAbsoluteFile() 返回的是File对象
* eclipse 默认绝对路径是工程目录
*/
public static void method3(){
File file = new File("F:\\java");
//获取绝对路径getAbsolutePath,返回的是字符串
String absolute = file.getAbsolutePath();
System.out.println(absolute);
//获取绝对路径getAbsoluteFile,返回的是File对象
File absoluteFile = file.getAbsoluteFile();
System.out.println(absoluteFile);
}
/*
* 获取,File构造方法中封装的路径的父路径
* String getParent() 返回的是String对象
* String getParentFile() 返回的是File对象
*/
public static void method2(){
File file = new File("F:\\zz.txt");
//获取父路径,方法getParent返回字符串
String parent = file.getParent();
System.out.println(parent);
//获取父路径,方法getParentFile返回File对象
File parentFile = file.getParentFile();
System.out.println(parentFile);
}
/*
* 获取,File构造方法中封装的路径的字符串
* String getPath()
* 路径变成字符串
*/
public static void method1(){
File file = new File("F:\\zz.txt");
//调用方法getPath获取路径字符串
String name = file.getPath();
System.out.println(name);
}
/*
* 获取,File构造方法中封装的路径的名字
* String getName()
* 获取的是路径最后一部分的名字
*/
public static void method(){
File file = new File("F:\\zz.txt");
//调用方法getName获取名
String name = file.getName();
System.out.println(name);
}
}
6. 高级获取功能
public String[] list()
public File[] listFiles()
案例演示
package file;
/*
* File类高级获取功能
* 方法开头list
*/
import java.io.*;
public class GaoJiHuoQu {
public static void main(String[] args) {
method();
method1();
method2();
}
/*
* 获取File构造方法中封装的路径下的文件和子目录 File[] listFiles() 全路径 返回的是存储File对象的数组
*/
public static void method2() {
File file = new File("F:\\eclipse");
// 调用方法listFiles()封装的路径下文件和子目录
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);
}
}
/*
* 获取File构造方法中封装的路径下的文件和子目录 String[] list() 对象调用,返回的存储字符串的数组
*/
public static void method1() {
File file = new File("F:\\eclipse");
// 调用方法list()获取,封装的路径下文件和子目录
String[] str = file.list();
for (String s : str) {
System.out.println(s);
}
}
/*
* 获取系统根目录 static File[] listRoots()
*/
public static void method() {
// 类名调用静态方法listRoots获取系统根
File[] files = File.listRoots();
for (File f : files) {
System.out.println(f);
}
}
}
7. 文件名称过滤器代码演示
package file;
import java.io.*;
public class Test {
public static void main(String[] args) {
method1();
}
public static void method1(){
File file = new File("F:\\demo");
//传递过滤器对象
File[] files = file.listFiles(new MyFilter());
for(File f : files){
System.out.println(f);
}
}
}
class MyFilter implements FileFilter{
public boolean accept(File pathname){
String name = pathname.getName().toLowerCase();
return name.endsWith(".txt");
}
}
运行结果:
-----------android培训、java培训、java学习型技术博客、期待与您交流!------------
一、异常
(一)异常概述
1. 异常:异常就是Java程序在运行过程中出现的错误。
2. 异常由来:问题也是现实生活中一个具体事务,也可以通过java 的类的形式进行描述,并封装成对象。其实就是Java对不正常情况进行描述后的对象体现。
3. 我们见过的异常,角标越界异常,空指针异常
(二)异常分类图解
1. 异常继承体系
java.lang.Throwable所有异常和错误的父类
Error类继Throwable
JAVA中所有错误的父类 -- 出现非常严重问题,不修改源代码,不能运行
理解:非典,艾滋,癌
Exception类继承Throwable
JAVA中所有异常的父类 -- 出现了比较轻微的问题,处理掉问题,程序继续执行
所有子类名字,后缀都是父类名字Exception
Exception下面继续分派系
RuntimeException 以及所有子类 运行异常
不是RuntimeException 编译异常
Throwable类方法
构造方法:
空参数的构造方法,没有任何异常信息
带有1个字符串参数,传递字符串表示异常的信息
成员方法:
String toString() 返回异常信息的简短描述,获取异常类名和异常信息,返回字符串。
String getMessage() 返回异常信息的详细描述,获取异常类名和异常信息,返回字符串。
void printStackTrace() 将异常追踪到标准输出流,将异常信息直接输在控制台
2. 异常举例
除数为0
数组访问越界
(三)JVM的默认处理方案
把异常的名称,错误原因及异常出现的位置等信息输出在了控制台
程序停止执行
(四)异常处理方案
1. try…catch…finally
格式:
try{
被检测的代码
可能出现异常代码
}catch(异常类 变量){
异常处理方式(写输出语句,调用方法,写判断,循环)
}
2. throw throws
throw 关键字含义:
表明方法内部会发送什么异常
如果参数传递不合法,可能导致程序不能继续执行手动抛出异常,告诉调用者,出现问题
throw写方法里面,后面new出来的异常对象
throws关键字含义
方法声明,表示有异常,请调用者处理
throws 写在方法声明上,后面写异常类的类名
throws和throw的区别
throws
用在方法声明后面,跟的是异常类名
可以跟多个异常类名,用逗号隔开
表示抛出异常,由该方法的调用者来处理
throws表示出现异常的一种可能性,并不一定会发生这些异常
throw
用在方法体内,跟的是异常对象名
只能抛出一个异常对象名
表示抛出异常,由方法体内的语句处理
throw则是抛出了异常,执行throw则一定抛出了某种异常
(五)编译时异常和运行时异常的区别
Java中的异常被分为两大类:编译时异常和运行时异常。所有的RuntimeException类及其子类的实例被称为运行时异常,其他的异常就是编译时异常
编译时异常:Java程序必须显示处理,否则程序就会发生错误,无法通过编译
运行时异常:无需显示处理,也可以和编译时异常一样处理,不需要throws声明,也不需要调用者处理。运行时异常,在程序正常运行的时候,是不能发生的。运行时期异常是不能出现的,如果出现了,必须修改源代码。
(六)finally
1. finally的特点
finally{} 不允许自己单独出现
被finally控制的语句体一定会执行
特殊情况:在执行到finally之前jvm退出了(比如System.exit(0))
2. finally的作用
用于释放资源,在IO流操作和数据库操作中会见到
(七)自定义异常类
定义类名字后缀是Exception,继承Exception或者RuntimeException
super异常信息,传递给父类构造方法
(八)异常注意事项
1. 子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。(父亲坏了,儿子不能比父亲更坏)
2. 如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
3. 如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
(九)案例
1. 除数为0,代码演示
package exception;
public class ExceptionChuShu {
public static void main(String[] args) {
try {
// 检测异常
int result = divide(5, 0);
System.out.println(result);
} catch (Exception ex) {
// 异常的处理方式
/*
* System.out.println(ex.toString());
* System.out.println(ex.getMessage());
*/
ex.printStackTrace();
}
System.out.println("over");
}
public static int divide(int a, int b) {
return a / b;
}
}
2. 空指针和数组越界异常(多个异常的平级现象)代码演示
package exception;
/*
* try…catch 多个异常的处理
* 平级现象:
* 出现的异常类之间,没有继承关系
* NullPointerException,ArrayIndexOutOfBoundsException
* Exception
* RuntimeException
* NullPointerException
* IndexOutOfBoundsException
* ArrayIndexOutOfBoundsException
*/
public class ExceptionArray {
public static void main(String[] args) {
try{
method(0);
}catch(ArrayIndexOutOfBoundsException ex){
System.out.println("出现数组越界");
ex.printStackTrace();
}catch(NullPointerException ex){
System.out.println("出现空指针");
ex.printStackTrace();
}
System.out.println("over");
}
/*
* 定义方法,抛出2个异常
* 空指针,数组越界
*/
public static void method(int x){
if(x==0){
//出现空指针
String s = null;
System.out.println(s.startsWith(""));
}else{
//出现数组越界异常
int[] arr = new int[0];
System.out.println(arr[2]);
}
}
}
3. 数组越界和集合越界(多异常,具有继承关系)代码演示
package exception;
import java.util.ArrayList;
import java.util.List;
/*
* try…catch 多异常处理,具有继承关系
* 数组越界
* ArrayIndexOutOfBoundsException
* 集合越界
* IndexOutOfBoundsException
* ArrayIndexOutOfBoundsException 继承自IndexOutOfBoundsException
* 继承关系中,类等级越高,写后面catch
*/
public class ExceptionExtends {
public static void main(String[] args) {
try {
method(1);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("出现数组越界异常");
ex.printStackTrace();
} catch (IndexOutOfBoundsException ex) {
System.out.println("出现集合越界异常");
ex.printStackTrace();
}
}
/*
* 定义方法,抛出异常 抛出数组越界,抛出集合越界
*/
public static void method(int x) {
if (x == 0) {
// 抛数组越界异常
int[] arr = new int[0];
System.out.println(arr[-1]);
} else {
// 抛出集合越界
List<String> list = new ArrayList<String>();
System.out.println(list.get(10));
}
}
}
4. throw与throws代码演示
package exception;
/*
* throw throws的使用方式
* throw方法内部手动抛出异常
* throws 方法声明,标识方法中有异常,请调用者处理
*/
public class ThrowAndThrows {
public static void main(String[] args) {
try {
abc(10, -20);
} catch (Exception ex) {
}
}
public static int abc(int a, int b) throws Exception {
return getAvg(a, b);
}
/*
* 传递两个成绩,计算平均分 成绩必须 >= 0 如果成绩非法,不要计算了,抛出异常 编译问题,方法内部抛出了异常,自己没有处理
* 我不想处理,让调用者处理
*/
public static int getAvg(int a, int b) throws Exception {
if (a < 0 || b < 0)
// 没有必要计算,直接手动抛出异常
throw new Exception("成绩小于0");
return (a + b) / 2;
}
}
5. 编译时期异常和运行时期异常代码演示
package exception;
public class CompileAndRun {
public static void main(String[] args) {
//method();//调用者必须处理
runtime();
int[] arr = null;
int max = sort(arr);
System.out.println(max);
}
// 传递数组,排序,返回数组最后索引,最大值
public static int sort(int[] arr) {
for (int x = 0; x < arr.length; x++) {
for (int y = x + 1; y < arr.length; y++) {
}
}
return arr[arr.length - 1];
}
// 方法内部抛出的运行时期异常,方法声明上不需要写throws
// 对于调用者,不需要处理
public static void runtime() {
// 手动抛出运行时期异常
throw new RuntimeException("!!!");
}
public static void method() throws Exception {
// 手动抛出编译时期异常
throw new Exception();
}
}
6. 运行时期异常的具体作用代码演示
package exception;
public class ExceptionFunction {
public static void main(String[] args) {
double d = 0;
d = getArea(-2);
System.out.println(d);
if(d > 10){
System.out.println("面积大于10");
}
}
/*
* 定义方法,计算圆形面积
* 半径平方乘以圆周率
* 半径传递参数
*/
public static double getArea(double r){
if( r < 0)
//抛出异常,传递参数非法,后面计算没有运行的必要的
throw new RuntimeException("半径不存在");
return r*r*Math.PI;
}
}
7. 自定义异常代码演示
package exception;
/*
* 自定义异常
* 计算圆形面积
* 半径 <= 0
* 异常问题,JAVA没有封装过异常对象
*
* 自己定义异常对象
*/
class FuShuException extends Exception {
FuShuException(String s) {
super(s);
}
}
class FuShuRuntimeException extends RuntimeException {
FuShuRuntimeException(String s) {
super(s);
}
}
public class ExceptionDefine {
public static void main(String[] args) {
try {
double d = getArea(-1.2);
System.out.println(d);
} catch (FuShuException ex) {
ex.printStackTrace();
}
getAreaRuntime(4.5);
}
public static double getAreaRuntime(double r) {
if (r <= 0)
// 半径问题,无法计算,抛出异常
throw new FuShuRuntimeException("半径不存在");
return r * r * Math.PI;
}
public static double getArea(double r) throws FuShuException {
if (r <= 0)
// 半径问题,无法计算,抛出异常
throw new FuShuException("半径不存在");
return r * r * Math.PI;
}
}
4. finally,证明:finally之前try return已经执行了
package exception;
public class ExceptionFinally {
public static void main(String[] args) {
int a = method();
System.out.println(a);
}
public static int method() {
int a = 1;
try {
return a;
} catch (Exception ex) {
} finally {
a = 7654;
System.out.println(a);
}
return a;
}
}
运行结果:
二、File类
(一)File类的概述
文件和目录路径名的抽象表示形式
(二)构造方法
public File(String pathname):传递字符串路径
public File(String parent,String child):传递字符串父路径,字符串子路径
public File(File parent,String child):传递File父路径,字符串子路径
代码演示
package file;
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
method();
method1();
method2();
}
public static void method2(){
File parent=new File("F:");
//创建File对象,传递File父路径,字符串子路径
File file = new File(parent,"eclipse");
System.out.println(file);
}
public static void method1(){
//创建File对象,传递字符串父路径,字符串子路径
File file= new File("F:","eclipse");
System.out.println(file);
}
public static void method(){
//创建File类对象,传递字符串路径
File file = new File("F:\\eclipse");
System.out.println(file);
}
}
运行结果:
(三)File类的成员方法
1. 创建功能
public boolean createNewFile():创建文件,创建成功返回true
public boolean mkdir():创建单级文件夹
public boolean mkdirs():创建多级文件夹
代码演示
package file;
import java.io.*;
public class SetUpFile {
public static void main(String[] args)throws IOException {
method();
method1();
}
public static void method1(){
File file = new File("F:\\hello");
boolean b=file.mkdir();
File file1 = new File("F:\\hello\\hello");
boolean b1=file1.mkdirs();
System.out.println(b);
System.out.println(b1);
}
public static void method()throws IOException{
File file = new File("F:\\zz.txt");
boolean b=file.createNewFile();
System.out.println(b);
}
}
演示结果:
2. 删除功能
public boolean delete():删除文件,删除文件夹
package file;
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
method();
}
public static void method(){
File file = new File("F:\\zz.txt");
//调用delete删除,删除的就是File构造方法中的封装的路径
boolean b = file.delete();
System.out.println(b);
}
}
运行结果:
3. 重命名功能
public boolean renameTo(File dest)
代码演示
package file;
import java.io.*;
public class RenameFile {
public static void main(String[] args) {
File file = new File("f:\\zz");
File dest = new File("f:\\ff");
boolean b=file.renameTo(dest);
System.out.println(b);
}
}
4. 判断功能
public boolean isDirectory():判断路径是不是目录
public boolean isFile():判断File构造方法中封装的路径是不是文件
public boolean exists():判断构造方法中路径是不是存在
public boolean canRead():判断文件能不能读取
public boolean canWrite():判断文件能不能写入
public boolean isHidden():判断File构造方法中封装的文件是不是隐藏属性
代码演示
package file;
/*
* File类判断方法
*/
import java.io.*;
public class JudgeFile {
public static void main(String[] args) {
method();
method1();
method2();
method3();
method4();
method5();
}
/*
* 判断File构造方法中封装的文件是不是能读,能写
* boolean canRead() 判断文件能不能读取
* boolean canWrite() 判断文件能不能写入
*/
public static void method5(){
File file = new File("F:\\zz.txt");
//调用方法canRead() 文件能不能读取
boolean b = file.canRead();
System.out.println(b);
//调用方法canWrite() 文件能不能被写入
boolean b1= file.canWrite();
System.out.println(b1);
}
/*
* 判断,File构造方法中封装的路径是不是绝对路径
* boolean isAbsolute(),路径是绝对,返回true
*/
public static void method4(){
File file = new File("f:\\zz.txt");
//调用方法 isAbsolute()判断路径是不是绝对的
boolean b = file.isAbsolute();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的文件是不是隐藏属性
* boolean isHidden() 文件是隐藏属性,返回true
*/
public static void method3(){
File file = new File("f:\\zz.txt");
//调用方法isHidden() 判断文件是不是隐藏属性
boolean b = file.isHidden();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的路径是不是文件
* boolean isFile(),构造方法中写的是文件,返回true
*/
public static void method2(){
File file = new File("f:\\java\\jre7");
//调用方法isFile() 构造方法中是不是文件
boolean b = file.isFile();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的路径是不是文件夹,即目录
* boolean isDirectory(),构造方法中写的是目录,返回true
*/
public static void method1(){
File file = new File("f:\\java");
//调用方法isDirectory判断路径是不是目录
boolean b = file.isDirectory();
System.out.println(b);
}
/*
* 判断,File构造方法中封装的路径是不是存在
* boolean exists() 如果存在返回true
*/
public static void method(){
File file = new File("f:\\java");
//调用方法exists,判断构造方法中路径是不是存在
boolean b = file.exists();
System.out.println(b);
}
}
5. 基本获取功能
public String getAbsolutePath()
public String getPath()
public String getName()
public long length()
public long lastModified()
代码演示
package file;
import java.io.*;
import java.text.DateFormat;
import java.util.*;
public class HuoQu {
public static void main(String[] args) {
method();
method1();
method2();
method3();
method4();
method5();
}
/*
* 获取文件最后一次修改时间毫秒值
* long lastModified()
* 获取File构造方法中封装的文件最后一次修改时间毫秒值
*/
public static void method5(){
File file = new File("F:\\java");
long l=file.lastModified();
//毫秒值--日期对象Date,Date格式化
Date date= new Date(l);
//System.out.println(date);
DateFormat dateFormat=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
String time= dateFormat.format(date);
System.out.println(time);
}
/*
* 获取文件字节长度
* long length
* 获取File构造方法中封装的文件字节数
*/
public static void method4(){
File file = new File("F:\\java");
//获取文件字节长度
long l=file.length();
System.out.println(l);
}
/*
* 获取,File构造方法中封装的路径的绝对路径
* String getAbsolutePath 返回的是String对象
* String getAbsoluteFile() 返回的是File对象
* eclipse 默认绝对路径是工程目录
*/
public static void method3(){
File file = new File("F:\\java");
//获取绝对路径getAbsolutePath,返回的是字符串
String absolute = file.getAbsolutePath();
System.out.println(absolute);
//获取绝对路径getAbsoluteFile,返回的是File对象
File absoluteFile = file.getAbsoluteFile();
System.out.println(absoluteFile);
}
/*
* 获取,File构造方法中封装的路径的父路径
* String getParent() 返回的是String对象
* String getParentFile() 返回的是File对象
*/
public static void method2(){
File file = new File("F:\\zz.txt");
//获取父路径,方法getParent返回字符串
String parent = file.getParent();
System.out.println(parent);
//获取父路径,方法getParentFile返回File对象
File parentFile = file.getParentFile();
System.out.println(parentFile);
}
/*
* 获取,File构造方法中封装的路径的字符串
* String getPath()
* 路径变成字符串
*/
public static void method1(){
File file = new File("F:\\zz.txt");
//调用方法getPath获取路径字符串
String name = file.getPath();
System.out.println(name);
}
/*
* 获取,File构造方法中封装的路径的名字
* String getName()
* 获取的是路径最后一部分的名字
*/
public static void method(){
File file = new File("F:\\zz.txt");
//调用方法getName获取名
String name = file.getName();
System.out.println(name);
}
}
6. 高级获取功能
public String[] list()
public File[] listFiles()
案例演示
package file;
/*
* File类高级获取功能
* 方法开头list
*/
import java.io.*;
public class GaoJiHuoQu {
public static void main(String[] args) {
method();
method1();
method2();
}
/*
* 获取File构造方法中封装的路径下的文件和子目录 File[] listFiles() 全路径 返回的是存储File对象的数组
*/
public static void method2() {
File file = new File("F:\\eclipse");
// 调用方法listFiles()封装的路径下文件和子目录
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);
}
}
/*
* 获取File构造方法中封装的路径下的文件和子目录 String[] list() 对象调用,返回的存储字符串的数组
*/
public static void method1() {
File file = new File("F:\\eclipse");
// 调用方法list()获取,封装的路径下文件和子目录
String[] str = file.list();
for (String s : str) {
System.out.println(s);
}
}
/*
* 获取系统根目录 static File[] listRoots()
*/
public static void method() {
// 类名调用静态方法listRoots获取系统根
File[] files = File.listRoots();
for (File f : files) {
System.out.println(f);
}
}
}
7. 文件名称过滤器代码演示
package file;
import java.io.*;
public class Test {
public static void main(String[] args) {
method1();
}
public static void method1(){
File file = new File("F:\\demo");
//传递过滤器对象
File[] files = file.listFiles(new MyFilter());
for(File f : files){
System.out.println(f);
}
}
}
class MyFilter implements FileFilter{
public boolean accept(File pathname){
String name = pathname.getName().toLowerCase();
return name.endsWith(".txt");
}
}
运行结果:
-----------android培训、java培训、java学习型技术博客、期待与您交流!------------
相关文章推荐
- 面试题
- 黑马程序员——Java基础---面向对象
- 黑马程序员——Java基础---继承,抽象,多态,接口,包,内部类
- 黑马程序员
- 黑马程序员——Java基础---集合
- 黑马程序员——高新技术---反射
- 黑马程序员
- 黑马程序员——Java基础---方法与数组操作
- 黑马程序员——Java基础---多线程
- Android面试题集锦
- 黑马程序员——多态
- 黑马程序员——组合与super关键字
- [程序员面试金典]1001.字符串变换
- 程序员装逼指南 (转)
- 黑马程序员——继承
- [程序员面试金典]1002.下一个较大元素
- 黑马程序员——self使用
- 黑马程序员——Java基础---常用类,基本类型包装类,正则表达式
- 【黑马程序员】protocol的概念及基本使用
- 黑马程序员——Java基础---IO、File类、Properties类、打印流、序列流(合并流)