try-catch-finally
package com.itheima.IO;
import java.io.*;
public class CopyTest5 {
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try {
System.out.println(10 / 0);
//1、创建一个字节输入管道与源文件接通
is = new FileInputStream("C:\\Users\\RCH\\Pictures\\Screenshots");
//2、创建一个字节输出流管道与目标文件接通
os = new FileOutputStream("D:\\z\\Screenshots");
System.out.println(10 / 0);
//3、创建一个字节数组,负责转移字节数据
byte[] buffer = new byte[1024];
//4、从字节输入流中读取字节数据,写出去到字节输出流中,读多少写出去多少
int len;//记住每次读取了多少个字节
while ((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
os.close();
is.close();
System.out.println("复制完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源的操作
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.itheima.释放内存;
public class test1 {
public static void main(String[] args) {
try {
System.out.println(10 /2);
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("===finally执行了一次===");
}
System.out.println(chu(10, 2));
}
public static int chu(int a, int b){
try {
return a / b;
}catch (Exception e){
e.printStackTrace();
return -1;//代表的是代码出现异常
}finally {
//千万不要在finally中返回数据
}
}
}
try-with-resource
package com.itheima.IO;
import java.io.*;
public class CopyTest5 {
public static void main(String[] args) {
try (
//1、创建一个字节输入管道与源文件接通
InputStream is = new FileInputStream("C:\\Users\\RCH\\Pictures\\Screenshots");
//2、创建一个字节输出流管道与目标文件接通
OutputStream os = new FileOutputStream("D:\\z\\Screenshots");
//注意:这里只能放置资源对象
//int age = 3;
//资源都是会实现AutoCloseable接口。资源都会有一个close方法,并且资源放到这里后
//用完之后,会被自动调用其close方法完成资源的释放操作
){
//3、创建一个字节数组,负责转移字节数据
byte[] buffer = new byte[1024];
//4、从字节输入流中读取字节数据,写出去到字节输出流中,读多少写出去多少
int len;//记住每次读取了多少个字节
while ((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
System.out.println("复制完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}