学习内容:学习JavaSE(Day14)
1、异常类结构
2、Exception的处理
3、自定义异常
4、File类
1、异常类结构
(1)异常的根类是Throwable类,它有两个直接子类:Error和Exception。
Error:如果程序出现错误,不能通过应用程序来解决。
Exception:如果程序出现xxxException,这个时候应该通过应用程序来解决(代码有问题)。
(2)RuntimeException:运行时异常,运行的时候出现的异常。
其他的异常:检查时异常,必须被 try{}catch语句块所捕获,或者在方法签名里通过throws子句声明。受检查的异常必须在编译时被捕捉处理,命名为 Checked Exception 是因为Java编译器要进行检查,Java虚拟机也要进行检查,以确保这个规则得到遵守。出现异常时会被红色波浪线标出。
(3)异常是由jdk中的jre的jvm(Java虚拟机)抛出的。
(4)异常中的方法:
PrintStackTrace():用于输出异常相关信息,包括异常的原因、产生异常的类文件的第几行代码。使用方法:e.printStackTrace();
getMessage() :返回异常的信息,但无法追踪到异常发生在代码第几行。使用方法:System.out.println(e.getMessage());
2、Exception的处理
(1)使用try{ }catch(异常类型){ }finally{ }捕获异常。
try {
String name = null;
System.out.println(name.length()); //空指针异常
int b = 12;
System.out.println(b / 0); //除数不能为0,否则报ArithmeticException异常
}catch (NullPointerException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally{
System.out.println("最终要执行的内容");b
}
System.out.println("end...");
运行结果:
java.lang.NullPointerException
at com.hisoft.test.Test.main(Test.java:11)
最终要执行的内容
end…
1.try块中捕获到异常后直接跳到catch,不会再看try块中下面的代码。
2.如果catch的异常类型有多个,并且有子父关系,子类异常要放在父类异常的前面,如果捕获的异常是平级关系,和顺序无关。
3.finally 块里的代码无论异常能否被处理,该程序都会被执行。
4.可以try{ }finally{ }使用,不写catch.
5.成功捕获异常后程序继续运行。
6.try{}catch( ){ }finally{ }都有返回值时,只返回finally中的返回值。
public static int getNum(){
try {
String name = null;
System.out.println(name.length());
return 1;
} catch (NullPointerException e) {
return 2;
} finally {
return 3;
}
}
返回值为 3
(2)使用throw关键字和throws关键字抛出异常。
public static void show() throws ActivationException{
int a = 0;
if (a == 0){
throw new ArithmeticException();
}else{
system.out.println(12/a);
}
system.out.println("end...");
}
出现ArithmeticException异常,程序终止运行。
1.throw关键字用于方法体中,throws关键字用于方法名。
2.抛出的异常是运行时异常时,程序直接终止运行。
3.抛出的异常为检查时异常时,那必须对该异常做处理,一般情况用throws。异常可以一直向上抛,直到jvm为止。
public static void show(){
File file = new File("c:/a.jpg");
//new FileInputStream提示未处理异常FileNotFoundException
//可能找不到该文件
FileInputStream fis = new FileInputStream(file);
}
可以用throws关键字向上抛出异常:
public static void show() throws FileNotFoundException{
File file = new File("c:/a.jpg");
FileInputStream fis = new FileInputStream(file);
}
异常被处理,错误消失,但是主函数在调用这个方法时还需要再向上抛出异常或捕获异常。当抛到jvm时会自动处理异常。
3、自定义异常
(1)自定义异常一般会继承RuntimeException或Exception。
自定义一个异常:
public class MyException extends Exception{
public MyException(){
super();
}
public MyException(String message){
super(message);
}
}
实体类中使用自定义异常:
public void setAge(Integer age) throws MyException { //throws处理异常
if (age <= 0) {
//使用自定义异常
throw new MyException("年龄不合法");
} else {
this.age = age;
}
}
测试自定义异常:
public static void main(String[] args) {
User user = new User();
try {
user.setAge(-10);
} catch (MyException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
运行结果:
年龄不合法
com.hisoft.exception.MyException: 年龄不合法
4、File类
(1)文件和目录路径名的抽象表示形式。用户界面和操作系统使用与系统相关的路径名字符串 来命名文件和目录。此类呈现分层路径名的一个抽象的、与系统无关的视图。
(2)separator :与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。
构造方法File:创建一个File实例。
System.out.println(File.separator);
File file = new File("D:" +File.separator+ "myPic/bad_egg.png");
File file1 = new File("D:/myPic/bad_egg.png");
File file2 = new File("d:/myPic","bad_egg.png");
File f = new File("D:/myPic");
File file3 = new File(f,"bad_egg.png");
运行结果:
filefile1file2==file3
(3)canExecute() :测试应用程序是否可以执行此抽象路径名表示的文件。
canRead() :测试应用程序是否可以读取此抽象路径名表示的文件。
canWrite() :测试应用程序是否可以修改此抽象路径名表示的文件。
compareTo(File pathname):按字母顺序比较两个抽象路径名。
createNewFile():当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件,返回boolean。
File file1 = new File("D:/myPic/bad_egg.png");
//创建新文件时会出现检查时异常
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
delete() :删除此抽象路径名表示的文件或目录。
equals(Object obj):测试此抽象路径名与给定对象是否相等。
exists():测试此抽象路径名表示的文件或目录是否存在。
getAbsoluteFile() :返回此抽象路径名的绝对路径名形式。
getAbsolutePath() :返回此抽象路径名的绝对路径名字符串。
两种方法返回的结果相同,但是一种是文件本身,一种是路径字符串。
File f = file.getAbsoluteFile();
System.out.println(f);
String path = file.getAbsolutePath();
System.out.println(path);
getFreeSpace():返回此抽象路径名指定的分区中未分配的字节数。剩余空间大小。
getName() :回由此抽象路径名表示的文件或目录的名称。
getParent():返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。返回String。
getParentFile() :回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录,则返回 null。返回File。
getPath() :此抽象路径名转换为一个路径名字符串。
getTotalSpace():返回此抽象路径名指定的分区大小。总空间大小。
getUsableSpace():返回此抽象路径名指定的分区上可用于此虚拟机的字节数。可用空间大小,一般与剩余空间大小相等。
isAbsolute():测试此抽象路径名是否为绝对路径名。
isDirectory():测试此抽象路径名表示的文件是否是一个目录。
isFile():测试此抽象路径名表示的文件是否是一个标准文件。
isHidden():测试此抽象路径名指定的文件是否是一个隐藏文件。
lastModified():返回此抽象路径名表示的文件最后一次被修改的时间。返回long时间戳。
length():返回由此抽象路径名表示的文件的长度。
list():返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。
如果这个路径名表示一个文件,file.list为null。
String[] files = file.list(); //返回该file中的文件或目录名称
mkdir() :创建此抽象路径名指定的目录。
File file = new File("d:/test/aa");
file.mkdir();
mkdirs() :建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
File file = new File("d:/test/aa/bb/cc");
file.mkdirs();
renameTo(File dest) :新命名此抽象路径名表示的文件。
setReadOnly() :记此抽象路径名指定的文件或目录,从而只能对其进行读操作。
setWritable(boolean writable) :置此抽象路径名所有者写权限的一个便捷方法。
setExecutable(boolean executable):设置此抽象路径名所有者执行权限的一个便捷方法。
(4)利用递归展示指定路径下所有文件和文件夹。
public static void showName(String path) {
File file = new File(path);
File[] files = file.listFiles();
if (files != null) {
for (File file1 : files) {
if (file1.isDirectory()) {
showName(file1.getPath());// 递归调用
} else {
System.out.println(file1.getName());
}
}
}
}
public static void main(String[] args) {
FileUtil.showName("C:/Windows");
}
5、LocalDateTime类
(1)在使用Date类获取的日期可读性差,需要使用SimpleDateFormat类进行格式化。但是SimpleDateFormat中的format是方法是线程不安全的,当多个线程同时使用相同的SimpleDateFormat对象调用format方法时,可能出现一个线程刚设置好的time值会被另一个线程修改的情况。
所以推荐使用JDK8新增的LocalDate、LocalTime、LocalDateTime类来获取时间。
(2)LocalDate:只会获取年月日。
LocalTime:只会获取几点几分几秒。
LocalDateTime:获取年月日时分秒,等于LocalDate+LocalTime。
Instant:获取秒数。
(3)
//获取当前日期:
LocalDate localDate = LocalDate.now();
//获取指定日期:
LocalDate localDate1 = LocalDate.of(2019, 9, 10);
//获取年份:
int year = localDate.getYear();
//获取月份:
Month month = localDate.getMonth();
//获取这天是本月第几天:
int day = localDate.getDayOfMonth();
//获取这天是星期几:
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
//获取小时
int hour = localTime.getHour();
//获取分
int minute = localTime.getMinute();
//获取秒
int second = localTime.getMinute();
//创建LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 = LocalDateTime.of(2019,Month.SEPTEMBER, 10, 14, 46, 56);
LocalDateTime localDateTime2 = LocalDateTime.of(localDate,localTime);
LocalDateTime localDateTime3 = localDate.atTime(localTime);
LocalDateTime localDateTime4 = localTime.atDate(localDate);
//创建Instant对象
Instant instant = Instant.now();
//获取秒数
long currentSecond = instant.getEpochSecond();
//获取毫秒数
long currentMilli = instant.toEpochMilli();
//获取毫秒数更方便
System.currentTimeMillis()
//增加一年
localDateTime = localDateTime.plusYears(1);
//减少一个月
localDateTime = localDateTime.minusMonths(1);
//修改年为2020
localDateTime = localDateTime.withYear(2020);
//格式化时间
//和SimpleDateFormat相比,DateTimeFormatter是线程安全的
LocalDate localDate3 = LocalDate.of(2019, 9, 10);
String s1 = localDate3.format(DateTimeFormatter.BASIC_ISO_DATE);
String s2 = localDate3.format(DateTimeFormatter.ISO_LOCAL_DATE);