简体   繁体   中英

How to copy files from one folder to another using Java?

How can I copy a file from one folder to another using java? I have tried to use

org.apache.commons.io.FileUtils.copyFileToDirectory(pasteItem, destinationPath);

This works if the destination folder does not contain a file with same name. It throws an IOException if I try to paste the file into the folder. However, is there any way to handle this? May be I want to just paste the file with name renamed automatically to pasteItem(1) or something like that. Please suggest.

In fact, I'm getting a new name for the file if the file with same name already exists. I'm not able to figure how to copy the file and then rename. If I rename first and then copy, I'll lose the original file. If I try to copy the file first, then it is giving an exception saying File with same name already exists!

You can use the Java.io.File class. It has a method that checks if a fill exists.

Example:

//create files
File original =new File("C:\\test\\testfile.txt");
File destination =new File("D:\\test\\file.txt");
//check if file exists.
for(int x=0;destination.exists()==true;x++){
//if file exists then add 1 to file name and check if exists again.
destination=new File("D\\test\\file"+x+".txt");

}
//copy file.
Files.copy(origional, destination, StandardCopyOption.REPLACE_EXISTING);

There is an overloaded version of this method using a boolean flag which will overwrite the destination file if true.

public static void copyFileToDirectory(File srcFile,
                   File destDir,
                   boolean preserveFileDate)
                            throws IOException

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFileToDirectory(java.io.File, java.io.File, boolean)

Please refer this site to copy a file from one folder to another. http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/

I am not sure about rename the file automatically

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM