1. 程式人生 > 實用技巧 >Java程式碼複製檔案

Java程式碼複製檔案

直接上程式碼

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class TestPrint26 {
    
    public static void main(String[] args) {
        
        String file1 = "D:\\ING\\172-26-223-soapui-project.xml";    //被複制的檔案
        String path = "C:\\ING";    //
新檔案路徑 String file2 = "newfile.xml"; //新檔名 copyFile(file1, path, file2); } /** * 把file1複製到file2 * @param file1 要被複制的檔案 * @param path 新檔案所在目錄 * @param file2 複製之後的新檔案 */ public static void copyFile(String file1, String path, String file2) { FileInputStream fis
= null; FileOutputStream fos = null; try { //新建file2的目錄 File fileDir = new File(path); if (!fileDir.exists()) { fileDir.mkdirs(); } //新建file2 File newFile = new File(path + "\\" + file2);
//新建兩個流 fis = new FileInputStream(file1); fos = new FileOutputStream(newFile); byte[] buf = new byte[1024]; //可以寫1024的倍數 int len = 0; while ((len = fis.read(buf)) != (-1)) { fos.write(buf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); //關閉流 } } catch (IOException e2) { e2.printStackTrace(); } try { if (fos != null) { fos.close(); //關閉流 } } catch (IOException e2) { e2.printStackTrace(); } } } }