java IO流 復制圖片。本站提示廣大學習愛好者:(java IO流 復制圖片)文章只能為提供參考,不一定能成為您想要的結果。以下是java IO流 復制圖片正文
(一)運用字節流復制圖片
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碼表中的值停止比照, 比照的時分會呈現二進制文件在碼表中找不對應的值,他會將二進制數據標志為未知字符,當我在寫入數據的是後會將未知的字符丟掉。所以會形成圖片拷貝不成功(喪失數據)
疑問:何時運用字節流?何時運用字符流?
運用字節流的場景:讀寫的數據不需求轉為我可以看得懂的字符。比方:圖片,視頻,音頻...
運用字符流的場景 :假如讀寫的是字符數據。