Copying files from one directory to another in Java

Posted in :

如何在 java 裡複製檔案:

For now this should solve your problem

File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
    FileUtils.copyDirectory(source, dest);
} catch (IOException e) {

FileUtils class from apache commons-io library, available since version 1.2.

Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.

一個一個檔案 copy 的話, 可以這樣做:

You can use this (or any variant):

Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);

Also, I’d recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.

Since you’re not sure how to temporarily store files, take a look at ArrayList:

List<File> files = new ArrayList();

To move a List of files into a single directory:

List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
        (new File(path + file.getName())).toPath(),


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *