gpt4 book ai didi

java - 删除文件并将其移动到java中的目录中

转载 作者:行者123 更新时间:2023-12-01 17:29:16 25 4
gpt4 key购买 nike

我正在尝试使用 java 中的 renameTo() 将文件从一个目录移动到另一个目录,但是 renameTo 不起作用(不重命名和移动文件)。基本上,我想先删除具有相同文件名的文件,然后将文件从另一个目录复制到我最初删除文件的同一位置,然后复制具有相同名称的新文件。

    //filePath = location of original file with file name appended. ex: C:\Dir\file.txt
//tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir

int pos = filePath.indexOf("C:\\Dir\\file.txt");
//Parse out only the path, so just C:\\Dir
String newFilePath = filePath.substring(0,pos-1);

//I want to delete the original file
File deletefile = new File(newFilePath,"file.txt");

if (deletefile.exists()) {
success = deletefile.delete();
}


//There is file already exists in the directory, but I am just appending .tmp at the end
File newFile = new File(tempPath + "file.txt" + ".tmp");

//Create original file again with same name.
File oldFile = new File(newFilePath, "file.txt");

success = oldFile.renameTo(newFile); // This doesnt work.

你能告诉我我做错了什么吗?

感谢您的帮助。

最佳答案

您需要转义字符串文字中的反斜杠:"C:\\Dir\\file.txt"。或者使用 File.separator 构建路径。

此外,确保 newFile 的路径构造正确:

File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp");
//^^^^^^^^^^^^^^^^

作为已发布代码中的注释(...例如:C:\AnotherDir)表明 tempPath 没有尾部斜杠字符。

关于java - 删除文件并将其移动到java中的目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12628875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com