Copying files from one directory to another in Java

如何在 java 裡複製檔案:
https://stackoverflow.com/questions/1146153/copying-files-from-one-directory-to-another-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) {
    e.printStackTrace();
}

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 的話, 可以這樣做:
https://stackoverflow.com/questions/16433915/how-to-copy-file-from-one-location-to-another-location

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();
files.add(foundFile);

To move a List of files into a single directory:

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

發佈留言

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