1. 程式人生 > 其它 >Java複製單級資料夾

Java複製單級資料夾

package com.czie.iot1913.lps.IO.BufferStream.Better;

import java.io.*;

/**
* FileName: CopyFileTest01 複製單級資料夾
* Author: lps
* Date: 2022/3/26 20:08
* Sign:劉品水 Q:1944900433
*/
public class CopyFileTest01 {
public static void main(String[] args) throws IOException{
// new File
File srcFolder = new File("E:\\itcast");

String srcFoldername = srcFolder.getName();

File destFolder = new File("F:\\JavaCode", srcFoldername);

//boolean exists()
//檢查檔案或目錄是否存在這種抽象路徑名記。
//!!!!!!!!!!!!!!!!!!
if (!destFolder.isDirectory()) {
destFolder.mkdir();
}
//boolean mkdir()
//建立該目錄下的抽象路徑名命名。

//File[] listFiles()
//返回表示抽象路徑名的目錄中的檔案的路徑名錶示抽象的陣列。 獲取資料來源目錄下所有檔案的File陣列
File[] listFiles = srcFolder.listFiles();

//該遍歷file陣列 得到file物件 (資料來源檔案)
for (File srcFile : listFiles) {
//獲取資料來源檔案File檔名稱
String srcFileName = srcFile.getName();
//建立目的地檔案file物件,路徑名是目的地+hh.jpg組成F:\\JavaCode\\itcast\\hh.jpg
//File(String parent, String child)
//建立從父路徑名的字串和一個孩子的一個新的 File例項檔案。
File deseFile = new File(destFolder, srcFileName);

copyFile(srcFile,deseFile);


}


}

private static void copyFile(File srcFile, File deseFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(deseFile));

byte[] bys = new byte[1024];
int len;
while ((len= bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bis.close();
bos.close();

}
}