![](/img/trans.png)
[英]How to open xlsx files stored in a folder one by one and copy data to another file using JAVA
[英]How to copy files from one folder to another using Java?
如何使用java将文件从一个文件夹复制到另一个文件夹? 我试过用
org.apache.commons.io.FileUtils.copyFileToDirectory(pasteItem, destinationPath);
如果目标文件夹不包含具有相同名称的文件,则此方法有效。 如果我尝试将文件粘贴到文件夹中,它会抛出IOException。 但是,有什么方法可以解决这个问题吗? 可能是我想将名称自动重命名的文件粘贴到pasteItem(1)或类似的东西。 请建议。
事实上,如果已存在同名文件,我将获得该文件的新名称。 我无法弄清楚如何复制文件然后重命名。 如果我先重命名然后复制,我将丢失原始文件。 如果我首先尝试复制文件,那么它会给出一个例外,说已存在同名文件!
您可以使用Java.io.File类。 它有一个检查填充是否存在的方法。
例:
//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);
这个方法的重载版本使用布尔标志,如果为true,将覆盖目标文件。
public static void copyFileToDirectory(File srcFile,
File destDir,
boolean preserveFileDate)
throws IOException
请参阅此站点将文件从一个文件夹复制到另一个文件夹。 http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/
我不确定是否自动重命名该文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.