简体   繁体   English

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

[英]Delete and move file to a directory in java

I am trying to move a file from one directory to another using renameTo() in java, however renameTo doesnt work (doesnt rename and move the file). 我正在尝试使用Java中的namedTo()将文件从一个目录移动到另一个目录,但是namedTo不起作用(不重命名并移动文件)。 Basically, I want to delete the file in one first with same file name, then copy a file from anoter directory to the same location where I deleted the file originally, then copy the new one with same name. 基本上,我想先删除一个具有相同文件名的文件,然后将文件从另一个目录复制到我最初删除该文件的位置,然后再复制一个具有相同名称的文件。

    //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.

Can you tell me what I am doing wrong? 你能告诉我我做错了什么吗?

Thanks for your help. 谢谢你的帮助。

You need to escape the backslashes in the string literal: "C:\\\\Dir\\\\file.txt" . 您需要在字符串文字中转义反斜杠: "C:\\\\Dir\\\\file.txt" Or use File.separator to construct the path. 或使用File.separator构造路径。

Additionally, ensure newFile 's path is constructed properly: 此外,请确保正确构造newFile的路径:

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

as the commments in the posted code ( ...ex: C:\\AnotherDir ) indicate that tempPath has no trailing slash character. 因为在已发布的代码( ...ex: C:\\AnotherDir )中的tempPath表明tempPath没有结尾的斜杠字符。

I have moved files to the destination directory and after moving deleted those moved files from source folder, in three ways, and at last am using the 3rd approach in my project. 我已经将文件移动到目标目录,并且在移动后以三种方式从源文件夹中删除了这些移动的文件,最后我在项目中使用了第三种方法。

1st approach: 第一种方法:

File folder = new File("SourceDirectory_Path");
    File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
    Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName()));
    }
    System.out.println("SUCCESS");

2nd approach: 第二种方法:

 Path sourceDir = Paths.get("SourceDirectory_Path");
    Path destinationDir = Paths.get("DestinationDerectory_Path");
      try(DirectoryStream<Path> directoryStream =   Files.newDirectoryStream(sourceDir)){
        for (Path path : directoryStream) {
            File d1 = sourceDir.resolve(path.getFileName()).toFile();
             File d2 = destinationDir.resolve(path.getFileName()).toFile(); 
             File oldFile = path.toFile();
            if(oldFile.renameTo(d2)){
                System.out.println("Moved");
            }else{
                System.out.println("Not Moved");
            }
        }
    }catch (Exception e) {
        e.printStackTrace();
    }

3rd approach: 第三种方法:

Path sourceDirectory= Paths.get(SOURCE_FILE_PATH);
            Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH);
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) {
                for (Path path : directoryStream) {                                    
                    Path dpath = destinationDirectory .resolve(path.getFileName());                                    
                    Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (IOException ex) {
                ex.printStackTrace();   
            }

Happy Coding !! 快乐编码! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM