檔案流,實現檔案複製
阿新 • • 發佈:2018-11-15
package com.io.demo1; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 檔案流,實現檔案複製 */ public class TestFfileCopy { public static void main(String[] args) { copyFile("d:/a.txt", "d:/b.txt"); } public static void copyFile(String src, String dec) { FileOutputStream fos = null; FileInputStream fis = null; byte[] buffer = new byte[1024]; int temp = 0; try { // 讀的檔案流 fis = new FileInputStream(src); // 要寫的檔案流 fos = new FileOutputStream(dec); //邊讀邊寫 //temp指的是本次讀取的真實長度,temp等於-1時表示讀取結束 while ((temp = fis.read(buffer)) != -1) { /** * 將快取陣列中的資料寫入檔案中,注意:寫入的是讀取的真實長度; * 如果使用fos.write(buffer)方法,那麼寫入的長度將會是1024,即快取 * 陣列的長度 * */ //存的是一個位元組組 fos.write(buffer, 0, temp); } for (byte item:buffer){ System.out.println(item); } } catch (Exception e) { e.printStackTrace(); } finally { //兩個流需要分別關閉(由於是兩個檔案流,所以需要關閉兩次) try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } }