我有一个程序应该将整个文件夹(带有子文件夹)中的所有文件重命名为临时文件名,将这些文件复制到另一个目录,然后将临时文件名更改回原始文件名。在此过程中,我想保持所有文件夹名称相同。当我运行下面的代码时,它只是更改我指定的路径中的顶级文件夹的名称:
package shortenFilenames;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class shortenFilenameClass
{
public static void main(String[] args) throws IOException
{
String absolutePathLocal = "C:\\Users\\talain\\Desktop\\marketingOriginal"; //original files
String absolutePathOnedrive= "C:\\Users\\talain\\Desktop\\fakeOnedrive"; //path to onedrive
File local = new File(absolutePathLocal);
File onedrive = new File(absolutePathOnedrive);
File[] filesInDir = local.listFiles();
for(int i = 0; i < filesInDir.length; i++)
{
String name = filesInDir[i].getName();
System.out.println(name);
String newName = String.valueOf(i);
File oldPath = new File(absolutePathLocal + "\\" + newName);
System.out.println("oldPath: " + oldPath);
filesInDir[i].renameTo(new File(oldPath.toString()));
File newPath = new File(absolutePathOnedrive + "\\" + newName);
copyFileUsingJava7Files(oldPath, newPath);
newPath.renameTo(new File(newPath.toString()));
System.out.println("renamed: " + name + "to: " + newName + ", copied to one drive, and changed back to original name");
}
}
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}
答案 0 :(得分:0)
我刚刚执行了以下操作,它将第一条路径中的所有文件复制到第二条路径中。如果它失败了,请告诉我错误输出。
for(int i = 0; i < filesInDir.length; i++)
{
String name = filesInDir[i].getName();
System.out.println(name);
Files.copy(new File(absolutePathLocal + "\\" + name).toPath(),new File(absolutePathOnedrive + "\\" + name).toPath());
}
您的代码还假设您的系统上已存在这些目录,否则您将遇到FileNotFound异常。