javaIO流中檔案的拷貝和圖片的拷貝
阿新 • • 發佈:2018-12-30
檔案拷貝例項:
利用檔案輸入輸出流編寫一個實現檔案拷貝的程式, 原始檔名和目標檔名通過控制檯輸入。
圖片拷貝例項:public class Copy { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("請輸入您要拷貝的原始檔:"); String str = sc.next(); System.out.print("請輸入您要拷貝的目標檔案:"); String s = sc.next(); /* * 方法一: * try { FileInputStream fis = new FileInputStream(str); byte[] b=new byte[fis.available()]; fis.read(b); System.out.println("原始檔內容:"); System.out.println(new String(b)); fis.close(); try { FileOutputStream fos = new FileOutputStream(s); String st = new String(b); fos.write(st.getBytes()); fos.flush(); fos.close(); System.out.println("檔案拷貝成功!"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { System.out.println("原始檔未找到!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //方法二: FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(str); fos = new FileOutputStream(s); byte[] b = new byte[fis.available()]; while (fis.read(b)!=-1) { fos.write(b); } System.out.println("檔案拷貝成功!"); } catch (FileNotFoundException e) { System.out.println("原始檔未找到!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(fis != null){ fis.close(); } if(fos != null){ fos.flush(); fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
將圖片根據原路徑拷貝到另一個路徑內
public class PictureCopy { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("E:/iodemo/99.jpg"); fos = new FileOutputStream("E:/iodemo/00.jpg"); byte [] b = new byte[fis.available()]; while (fis.read(b)!=-1) { fos.write(b); } fos.close(); System.out.println("圖片拷貝成功!"); } catch (FileNotFoundException e) { System.out.println("原始檔未找到!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //finally關鍵字:無論出不出現異常最後都要執行finally語句中的程式碼 //最後再關閉流 try { if(fis!=null){ fis.close(); } if(fos != null){ fos.flush(); fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }