Java 內建沒有檔案複製的 API,原本想直接用 Linux 的 cp -r
(因為我們公司的環境是在 Linux 上跑 Java 的 Web Application)
但怎麼試都試不出在 Java 裡面透過 Runtime 來下 cp 可以把某個資料夾內所有檔案複製到指定目錄
好像是因為 Runtime 不能用 * 這種字元,然後改成寫 shell script 從 Java 呼叫也還是有問題
所以只好自己寫一個~
其實說是自己寫一個,因為實在懶得寫 XD,所以直接找了人家寫好的 code 來小改一下!
參考資料:JAVA COPY整個資料夾
整體結構跟上面連結的程式碼一模一樣,只是改了一點點 error handling 跟習慣的變數用法。
public class FileCopy {
public void copyFile (File sourceFile, File destinationFile) throws IOException {
if(sourceFile.isDirectory())
this.copyDirectory(sourceFile, destinationFile);
else if(destinationFile.isDirectory())
throw new IOException("Cannot copy a file to a directory.");
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destinationFile);
// Copy content of files
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
public void copyDirectory(File sourceDir, File destinationDir) throws IOException{
if(sourceDir.isFile())
this.copyFile(sourceDir, destinationDir);
else if(destinationDir.isFile())
throw new IOException("Cannot copy a directory to a file.");
File[] fileList = sourceDir.listFiles();
for (File currentFile : fileList) {
if(currentFile.isFile()) {
/* -------------------------- */
/* Copy files in the folder */
/* -------------------------- */
File destDemo = new File(destinationDir.getAbsolutePath() + "/" + currentFile.getName());
this.copyFile(currentFile, destDemo);
}
else {
File destDemo = new File(destinationDir.getAbsolutePath() + "/" + currentFile.getName());
destDemo.mkdirs();
this.copyDirectory(currentFile, destDemo);
}
}
}
}
沒有留言:
張貼留言