How to copy file from one location to another location?

后端 未结 6 964
攒了一身酷
攒了一身酷 2020-11-28 23:02

I want to copy a file from one location to another location in Java. What is the best way to do this?


Here is what I have so far:

import java.i         


        
6条回答
  •  醉酒成梦
    2020-11-28 23:09

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

    To move a List of files into a single directory:

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

提交回复
热议问题