歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java IO流 復制圖片

Java IO流 復制圖片

日期:2017/3/1 9:08:29   编辑:Linux編程

(一)使用Java IO字節流復制圖片

//字節流方法
public static void copyFile()throws IOException {

//1.獲取目標路徑
//(1)可以通過字符串
// String srcPath = "C:\\Users\\linuxidc\\Desktop\\截圖筆記\\11.jpg";
// String destPath = "C:\\Users\\linuxidc\\Desktop\\圖片備份\\11.jpg";

//(2)通過文件類
File srcPath = new File("C:\\Users\\linuxidc\\Desktop\\截圖筆記\\22.PNG");
File destPath = new File("C:\\Users\\linuxidc\\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\\linuxidc\\Desktop\\截圖筆記\\33.PNG");
File destPath = new File("C:\\Users\\linuxidc\\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\\linuxidc\\Desktop\\截圖筆記\\55.PNG");
File destPath = new File("C:\\Users\\linuxidc\\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碼表中的值進行對比, 對比的時候會出現二進制文件在碼表中找不對應的值,他會將二進制數據標記為未知字符,當我在寫入數據的是後會將未知的字符丟掉。所以會造成圖片拷貝不成功(丟失數據)

疑問:何時使用字節流?何時使用字符流?

使用字節流的場景:讀寫的數據不需要轉為我能夠看得懂的字符。比如:圖片,視頻,音頻...

使用字符流的場景 :如果讀寫的是字符數據。

Copyright © Linux教程網 All Rights Reserved