Search code examples
javafiledirectorysystem

How to move folder and files?


My program uses a file database and I was wondering how to move a folder without deleting the files from within the folder. I am using java. When I press a button I would like them to move to a specified location. The code on the button looks like this:

private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    ProjectInfo.documentTitle = fileName.getText();
    ProjectInfo.moveFileLocation = fileSpecificLocation.getText();
    String name = userNameText.getText();
    Signup.fileToMoveTo = "C:\\CloudAurora\\" + name + "\\";
    String docTtl = ProjectInfo.documentTitle;

    // docTtl.renameTo(new File(Signup.fileToMoveTo));

    ProjectInfo.documentTitle = fileName.getText();
    ProjectInfo.moveFileLocation = fileSpecificLocation.getText();
    String name = userNameText.getText();
    Signup.fileToMoveTo = "C:\\CloudAurora\\" + name + "\\";
    String docTtl = ProjectInfo.documentTitle;
    System.out.println(ProjectInfo.documentTitle);
    System.out.println(Signup.fileToMoveTo);
}

If Someone could help that would be awesome. I have looked for a way to do it but couldn't figure out how


Solution

  • I hope as per your case, I have mentioned the source file and destination file correctly. Below code should move the folders along with the file.

    File srcFile = new File(docTtl);
    File destFile = new File(Signup.fileToMoveTo);
    
    /* Handle IOException for the below line */
    Files.move(Paths.get(srcFile.getPath()), Paths.get(destFile.getPath()), StandardCopyOption.REPLACE_EXISTING);