(一)使用字節流復制圖片
1 //字節流方法
2 public static void copyFile()throws IOException {
3
4 //1.獲取目標路徑
5 //(1)可以通過字符串
6 // String srcPath = "C:\\Users\\bigerf\\Desktop\\截圖筆記\\11.jpg";
7 // String destPath = "C:\\Users\\bigerf\\Desktop\\圖片備份\\11.jpg";
8
9 //(2)通過文件類
10 File srcPath = new File("C:\\Users\\bigerf\\Desktop\\截圖筆記\\22.PNG");
11 File destPath = new File("C:\\Users\\bigerf\\Desktop\\圖片備份\\22.PNG");
12
13 //2.創建通道,依次 打開輸入流,輸出流
14 FileInputStream fis = new FileInputStream(srcPath);
15 FileOutputStream fos = new FileOutputStream(destPath);
16
17 byte[] bt = new byte[1024];
18
19 //3.讀取和寫入信息(邊讀取邊寫入)
20 while (fis.read(bt) != -1) {//讀取
21 fos.write(bt);//寫入
22 }
23
24 //4.依次 關閉流(先開後關,後開先關)
25 fos.close();
26 fis.close();
27 }
(二)使用字符流復制文件
1 //字符流方法,寫入的數據會有丟失
2 public static void copyFileChar()throws IOException {
3
4 //獲取目標路徑
5 File srcPath = new File("C:\\Users\\bigerf\\Desktop\\截圖筆記\\33.PNG");
6 File destPath = new File("C:\\Users\\bigerf\\Desktop\\圖片備份\\33.PNG");
7
8 //創建通道,依次 打開輸入流,輸出流
9 FileReader frd = new FileReader(srcPath);
10 FileWriter fwt = new FileWriter(destPath);
11
12 char[] ch = new char[1024];
13 int length = 0;
14 // 讀取和寫入信息(邊讀取邊寫入)
15 while ((length = frd.read(ch)) != -1) {//讀取
16 fwt.write(ch,0,length);//寫入
17 fwt.flush();
18 }
19
20 // 依次 關閉流(先開後關,後開先關)
21 frd.close();
22 fwt.close();
23 }
(三)以復制圖片為例,實現拋出異常案例
1 //以復制圖片為例,實現try{ }cater{ }finally{ } 的使用
2 public static void test(){
3 //1.獲取目標路徑
4 File srcPath = new File("C:\\Users\\bigerf\\Desktop\\截圖筆記\\55.PNG");
5 File destPath = new File("C:\\Users\\bigerf\\Desktop\\圖片備份\\55.PNG");
6 //2.創建通道,先賦空值
7 FileInputStream fis = null;
8 FileOutputStream fos = null;
9 //3.創建通道時需要拋出異常
10 try {
11 fis = new FileInputStream(srcPath);
12 fos = new FileOutputStream(destPath);
13
14 byte[] bt = new byte[1024];
15 //4.讀取和寫入數據時需要拋出異常
16 try {
17 while(fis.read(bt) != -1){
18 fos.write(bt);
19 }
20 } catch (Exception e) {
21 System.out.println("儲存盤異常,請修理");
22 throw new RuntimeException(e);
23 }
24
25
26 } catch (FileNotFoundException e) {
27 System.out.println("資源文件不存在");
28 throw new RuntimeException(e);
29 }finally{
30
31 //5.無論有無異常,需要關閉資源(分別拋出異常)
32 try {
33 fos.close();
34 } catch (Exception e) {
35 System.out.println("資源文件或目標文件關閉失敗!");
36 throw new RuntimeException(e);
37 }
38
39 try {
40 fis.close();
41 } catch (IOException e) {
42 System.out.println("資源文件或目標文件關閉失敗!");
43 throw new RuntimeException(e);
44 }
45
46 }
47 }
字符流 = 字節流 + 解碼 --->找對應的碼表 GBK
字符流解碼 : 拿到系統默認的編碼方式來解碼
將圖片中的二進制數據和GBK碼表中的值進行對比, 對比的時候會出現二進制文件在碼表中找不對應的值,他會將二進制數據標記為未知字符,當我在寫入數據的是後會將未知的字符丟掉。所以會造成圖片拷貝不成功(丟失數據)
疑問:何時使用字節流?何時使用字符流?
使用字節流的場景:讀寫的數據不需要轉為我能夠看得懂的字符。比如:圖片,視頻,音頻...
使用字符流的場景 :如果讀寫的是字符數據。