標籤:gbk 標記 runtime byte cep otf flush new 需要
一.使用位元組流複製圖片
//位元組流方法 public static void copyFile()throws IOException { //1.擷取目標路徑 //(1)可以通過字串 // String srcPath = "E://11.jpg"; // String destPath = "E://22.jpg"; //(2)通過檔案類 File srcPath = new File("E://11.jpg"); File destPath = new File("E://22.jpg"); //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("E://11.jpg");
File destPath = new File("E://22.jpg"); //建立通道,依次 開啟輸入資料流,輸出資料流 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("E://11.jpg");
File destPath = new File("E://11.jpg");
//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碼錶中的值進行對比, 對比的時候會出現二進位檔案在碼錶中找不對應的值,他會將位元據標記為未知字元,當我在寫入資料的是後會將未知的字元丟掉。所以會造成圖片拷貝不成功(遺失資料) 疑問:何時使用位元組流?何時使用字元流? 使用位元組流的情境:讀寫的資料不需要轉為我能夠看得懂的字元。比如:圖片,視頻,音頻... 使用字元流的情境 :如果讀寫的是字元資料。 |
java IO流複製圖片