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

标签 java file-io

我正在尝试使用 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/

相关文章:

java - 这也是匿名派生类的例子吗? (Java 基础知识)

c - 解析 C 文件 I/O

java - 我如何在java中读取特定数据

java - 我必须从数据库中获取 500K 行并将该数据写入文件,意味着执行 I/O 操作

c# - 如何将文件中特定偏移量的字节复制到特定偏移量的另一个文件?

java - 时间快照的数据结构

java - 本地样式表和脚本未加载 JAVA

java - Android junit : Method scheme in android.net.Uri&Builder 未模拟

java - 从 jframe 打开网页

java - 变量可能还没有初始化?