需求:拷贝一份文件
要求:
1. 边读边写,不能将文件数据全部读取完毕后,再写出
2. 处理程序可能出现的异常
提示:
1. 处理的异常的目的(步骤):
(1)阻止下面代码的执行(结束程序)
(2)通知调用者这里出现了错误
2. throw RuntimeException(IOException e);
(1) 将 IOException异常传递给 RuntimeException包装一层,然后再抛出。这样做的目的是为了让调用者使用变得更灵活。
(2) RuntimeException运行时异常,出现这种异常时,jvm会自动阻断后边程序的运行,并将异常信息通知给调用者。
public class Dome1 {
public static void main(String[] args) {
// 1.找到目标文件
File readFile = new File("E:\\aa\\bb\\aaaa.wmv");
File writeFile = new File("E:\\aa\\bb\\复制品.wmv");
// 2.搭建数据通道
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(readFile);
fileOutputStream = new FileOutputStream(writeFile);
// 3.传输数据
byte[] bytes = new byte[1024];//构建缓冲数组读取数据,缓冲数组的容量一般是1024的倍数
int len = 0;//声明变量,用于存储每次读取的数据
while ((len = fileInputStream.read()) != -1) {//读取文件内容
//读一次写一次,len是每次读写的容量,FileOutputStream每次创建新的对象指针默认会指向文件的开始位置,同一个对象每次写出时,指针会根据每次写出,出现相应的移动。
fileOutputStream.write(bytes, 0, len);//写出,
}
} catch (IOException e) {
/*
处理的异常的目的(步骤):
1.阻止下面代码的执行(结束程序)
2.通知调用者这里出现了错误
throw RuntimeException(IOException e);
将 IOException异常传递给 RuntimeException包装一层,然后再抛出。这样做的目的是为了让调用者使用变得更灵活。
RuntimeException运行时异常,出现这种异常时,jvm会自动阻断后边程序的运行,并将异常信息通知给调用者。
*/
System.out.println("拷贝文件出错......");
throw new RuntimeException(e);//处理异常,将 fileNotFoundException异常包装到运行时异常Runtimeexception中,当出现运行时异常时,会结束程序运行
} finally {
// 4.释放资源
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("关闭输出流 fileOutputStream 资源成功......");
}
} catch (IOException e) {
System.out.println("关闭输出流 fileOutputStream 资源失败......");
throw new RuntimeException(e);
} finally {
try {
if (fileInputStream != null) {
System.out.println("关闭输入流 FileInputStream 资源成功......");
fileInputStream.close();
}
} catch (IOException e) {
System.out.println("关闭输入流 FileInputStream 资源失败......");
throw new RuntimeException(e);
}
}
}
}
}