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

Ton*_*ony 0 java file-io

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

    //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.
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助.

hmj*_*mjd 5

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

另外,确保newFile路径构造正确:

File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp");
                               //^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

由于已发布的代码(...ex: C:\AnotherDir)中的提交表明tempPath没有尾部斜杠字符.