java IO流 复制图片

时间:2022-05-19 13:50:10

(一)使用字节流复制图片

 //字节流方法
public static void copyFile()throws IOException { //1.获取目标路径
//(1)可以通过字符串
// String srcPath = "C:\\Users\\bg\\Desktop\\截图笔记\\11.jpg";
// String destPath = "C:\\Users\\bg\\Desktop\\图片备份\\11.jpg"; //(2)通过文件类
File srcPath = new File("C:\\Users\\bg\\Desktop\\截图笔记\\22.PNG");
File destPath = new File("C:\\Users\\bg\\Desktop\\图片备份\\22.PNG"); //2.创建通道,依次 打开输入流,输出流
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath); byte[] bt = new byte[1024]; //3.读取和写入信息(边读取边写入)
while (fis.read(bt) != -1) {//读取
fos.write(bt);//写入
} //4.依次 关闭流(先开后关,后开先关)
fos.close();
fis.close();
}

(二)使用字符流复制文件

 //字符流方法,写入的数据会有丢失
public static void copyFileChar()throws IOException { //获取目标路径
File srcPath = new File("C:\\Users\\bg\\Desktop\\截图笔记\\33.PNG");
File destPath = new File("C:\\Users\\bg\\Desktop\\图片备份\\33.PNG"); //创建通道,依次 打开输入流,输出流
FileReader frd = new FileReader(srcPath);
FileWriter fwt = new FileWriter(destPath); char[] ch = new char[1024];
int length = 0;
// 读取和写入信息(边读取边写入)
while ((length = frd.read(ch)) != -1) {//读取
fwt.write(ch,0,length);//写入
fwt.flush();
} // 依次 关闭流(先开后关,后开先关)
frd.close();
fwt.close();
}

(三)以复制图片为例,实现抛出异常案例

     //以复制图片为例,实现try{ }cater{ }finally{ } 的使用
public static void test(){
//1.获取目标路径
File srcPath = new File("C:\\Users\\bg\\Desktop\\截图笔记\\55.PNG");
File destPath = new File("C:\\Users\\bg\\Desktop\\图片备份\\55.PNG");
//2.创建通道,先赋空值
FileInputStream fis = null;
FileOutputStream fos = null;
//3.创建通道时需要抛出异常
try {
fis = new FileInputStream(srcPath);
fos = new FileOutputStream(destPath); byte[] bt = new byte[1024];
//4.读取和写入数据时需要抛出异常
try {
while(fis.read(bt) != -1){
fos.write(bt);
}
} catch (Exception e) {
System.out.println("储存盘异常,请修理");
throw new RuntimeException(e);
} } catch (FileNotFoundException e) {
System.out.println("资源文件不存在");
throw new RuntimeException(e);
}finally{ //5.无论有无异常,需要关闭资源(分别抛出异常)
try {
fos.close();
} catch (Exception e) {
System.out.println("资源文件或目标文件关闭失败!");
throw new RuntimeException(e);
} try {
fis.close();
} catch (IOException e) {
System.out.println("资源文件或目标文件关闭失败!");
throw new RuntimeException(e);
} }
}

字符流  =  字节流 + 解码 --->找对应的码表  GBK

字符流解码 : 拿到系统默认的编码方式来解码

将图片中的二进制数据和GBK码表中的值进行对比, 对比的时候会出现二进制文件在码表中找不对应的值,他会将二进制数据标记为未知字符,当我在写入数据的是后会将未知的字符丢掉。所以会造成图片拷贝不成功(丢失数据)

疑问:何时使用字节流?何时使用字符流?

使用字节流的场景:读写的数据不需要转为我能够看得懂的字符。比如:图片,视频,音频...

使用字符流的场景 :如果读写的是字符数据。