我试图在重命名文件后将文件从 1 个目录复制到另一个目录,但不断收到错误消息:
Exception in thread "main" java.nio.file.NoSuchFileException: C:\Users\talain\Desktop\marketingOriginal\FX Rates\FY17\Q11\Week_12___February_12_2016.xls -> C:\Users\talain\Desktop\fakeOnedrive\FX Rates\FY17\Q11\0
我的代码:
public class shortenFilenameClass
{
static String absolutePathLocal = "C:\\Users\\talain\\Desktop\\marketingOriginal".replace('\\', '/'); //path to original files
static String absolutePathOnedrive= "C:\\Users\\talain\\Desktop\\fakeOnedrive".replace('\\', '/'); //path to onedrive
public static void main(String[] args) throws IOException
{
System.out.println(absolutePathLocal.length());
File local = new File(absolutePathLocal);
File onedrive = new File(absolutePathOnedrive);
int fileCount = 0;
File[] filesInDir = local.listFiles();
manipulateFiles(filesInDir, fileCount);
}
public static void manipulateFiles(File[] filesInDirPassed, int fileCount) throws IOException
{
for(int i = 0; i < filesInDirPassed.length; i++)
{
File currentFile = filesInDirPassed[i];
if(currentFile.isDirectory())
{
String local = currentFile.getAbsolutePath();
//String onedrive = current
manipulateFiles(currentFile.listFiles(), fileCount);
}
String name = currentFile.getName();
System.out.println("old filename: " + name);
String newName = String.valueOf(fileCount);
fileCount++;
File oldPath = new File(currentFile.getAbsolutePath());
System.out.println("oldPath: " + oldPath);
//currentFile.renameTo(new File(oldPath.toString()));
System.out.println("currentFile: " + currentFile);
String pathExtension = new String(currentFile.getAbsolutePath().substring(42));
pathExtension = pathExtension.replaceAll(name, newName);
File newPath = new File(absolutePathOnedrive + "/" + pathExtension);
System.out.println("newPath: " + newPath);
copyFileUsingJava7Files(oldPath, newPath);
File finalPath = new File(absolutePathOnedrive + "" + name);
//newPath.renameTo(new File(finalPath.toString()));
//copyFileUsingJava7Files(newPath, finalPath);
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());
}
}