《黑馬程式設計師》 IO之複製圖片
阿新 • • 發佈:2019-01-31
class Demo9 { /* 複製圖片 複製d盤的圖片到e盤中 像多媒體檔案及圖片資源,操作它最好使用位元組流 因為使用字元流可能會出現無法瀏覽的情況 */ public static void main(String[] args) { File src=new File("d:\\temp.png"); //獲取原始檔絕對路徑 String srcPath=src.getAbsolutePath(); //獲取檔案路徑擷取檔名然後組拼成新的檔案路徑 String destPath="e:\\"+srcPath.substring(srcPath.lastIndexOf("\\")+1); File dest=new File(destPath); copyPic(src,dest); } public static void copyPic(File src,File dest){ InputStream fis=null; //要進行初始化 OutputStream fos=null; //要進行初始化 try{ fis=new FileInputStream(src); fos=new FileOutputStream(dest); //建立緩衝區 byte[] buffer=new byte[1024]; int len; //記錄讀取到的資料的個數 while((len=fis.read(buffer))!=-1){ //把讀取到的資料寫入到檔案中 //只寫緩衝區中的有效位 fos.write(buffer,0,len); } //關閉流:雖說可以不關,但是關上還是好一些 fis.close(); fos.close(); }catch(Exception e){ e.printStackTrace(); } } }