java的輸入輸出流與檔案操作(3 .檔案拷貝)
阿新 • • 發佈:2019-02-05
/* * 拷貝檔案: 從一個檔案讀取資料,寫到另一個檔案,迴圈進行“邊讀邊寫” * 1.文字檔案 * 2.二進位制檔案:影象、聲音、可執行程式類 * */ @Test public void TestCopy() { FileInputStream in = null; FileOutputStream out = null; byte[] buf = new byte[1024]; int len = 0; try { in = new FileInputStream("E:/test/1.jpg"); out = new FileOutputStream("E:/test/2.jpg"); while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { throw new RuntimeException("關閉輸入流失敗!", e); } try { if (out != null) { out.close(); } } catch (IOException e) { throw new RuntimeException("關閉輸出流失敗!", e); } } }