Tony
Tony

Reputation: 3409

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

Upvotes: 0

Views: 3757

Answers (2)

Soumya Sarkar
Soumya Sarkar

Reputation: 95

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 !! :)

Upvotes: 0

hmjd
hmjd

Reputation: 121971

You need to escape the backslashes in the string literal: "C:\\Dir\\file.txt". Or use File.separator to construct the path.

Additionally, ensure newFile's path is constructed properly:

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.

Upvotes: 5

Related Questions