进阶day09-JDK7,9的IO异常处理方式

This commit is contained in:
2026-03-21 15:37:22 +08:00
parent 8b1e6f5b7e
commit 077745e892
5 changed files with 133 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
package com.inmind.io_exception05;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//jdk7之前的标准代码
public class Demo14 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//创建流对象(输入,输出)
fis = new FileInputStream("D:\\io_test\\upload\\1.jpg");
fos = new FileOutputStream("D:\\io_test\\upload\\3.jpg");
//不停地读取一个字节数组,写出一个字节数组,直到读完
int len;//保存读取到的字节的个数
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes,0,len);//读多少个字节,一次性写出多少个字节
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
//资源释放
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
fis = null;//当前流已经关闭如果不设置为nullfis可能会引用这堆内存中的一个无用liu对象造成内存泄漏
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
fos = null;
}
}
}
}

View File

@@ -0,0 +1,33 @@
package com.inmind.io_exception05;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
JDK7异常的处理方式(了解)
格式:
try(流的创建方式){
}catch{
}
作用当try-cath代码执行完毕程序会自动去调用try(流的创建方式)的close方法
*/
public class Demo15 {
public static void main(String[] args) {
//创建字节输入流
try (FileInputStream fis = new FileInputStream("a.txt")) {
//不停地读字节
int c ;//保存读取的字节数据
while ((c = fis.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,18 @@
package com.inmind.io_exception05;
import java.io.FileInputStream;
import java.io.IOException;
public class Demo16 {
public static void main(String[] args) {
//创建字节输入流
try (Student s = new Student()) {
System.out.println("try中的代码执行了");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("程序结束");
}
}

View File

@@ -0,0 +1,27 @@
package com.inmind.io_exception05;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
JDK9的IO异常处理改进(了解)
作用当try-cath代码执行完毕程序会自动去调用try(流的创建方式)的close方法
*/
public class Demo17 {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("a.txt");
//创建字节输入流
try (fis) {
//不停地读字节
int c ;//保存读取的字节数据
while ((c = fis.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,8 @@
package com.inmind.io_exception05;
public class Student implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("Student类的close方法执行了");
}
}