Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving files from one directory to another with Java NIO

I am using the NIO libraries but I am getting a strange error when I try to move files from one directory to another.

String yearNow = new SimpleDateFormat("yyyy").format(
    Calendar.getInstance().getTime());

try {
     DirectoryStream<Path> curYearStream = 
       Files.newDirectoryStream(sourceDir, "{" + yearNow + "*}"); 
       //Glob for current year

     Path newDir = Paths.get(sourceDir + "//" + yearNow);

     if (!Files.exists(newDir) || !Files.isDirectory(newDir)) {
         Files.createDirectory(newDir); 
         //create 2014 directory if it doesn't exist
     }
}

Iterate over elements that start with "2014" and move them in the new directory (newDir, which is also called 2014)

for (Path p : curYearStream) {
    System.out.println(p); //it prints out exactly the files that I need to move
    Files.move(p, newDir); //java.nio.file.FileAlreadyExistsException
}

I get the java.nio.file.FileAlreadyExistsException because my folder (2014) already exists. What I actually want to do is move all the files that start with "2014" INSIDE the 2014 directory.

like image 671
Gregg1989 Avatar asked Mar 12 '14 15:03

Gregg1989


People also ask

How to move all files from one directory to another in Java?

This post will discuss how to move all files from one directory to another in Java. 1. Using FileUtils.moveDirectory () method For copying or moving a directory to another location, you can use third-party libraries like Apache Commons IO whose FileUtils class offers several file manipulation utilities.

What are the file handling methods in Java using NIO?

There are quite a few File Handling methods in Java using the NIO package. Let us glide through a few along with a small example of its implementation. File.exists (): Checks whether the file (path of the file) exists in the System or not. File.createDirectory () : Creates a new directory from the file path instance.

How to move a file from one location to another?

The first method utilizes Files package for moving while the other method first copies the file to destination and then deletes the original copy from the source. Using Files.Path move () method: Renaming and moving the file permanently to a new location.

How to move file from one directory to another in Python?

We can use Files.move () API to move file from one directory to another. Following is the syntax of the move method.


3 Answers

Better not going back to java.io.File and using NIO instead:

    Path sourceDir = Paths.get("c:\\source");
    Path destinationDir = Paths.get("c:\\dest");

    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)) {
        for (Path path : directoryStream) {
            System.out.println("copying " + path.toString());
            Path d2 = destinationDir.resolve(path.getFileName());
            System.out.println("destination File=" + d2);
            Files.move(path, d2, REPLACE_EXISTING);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
like image 199
Andrew Avatar answered Oct 05 '22 23:10

Andrew


Files.move is not equivalent to the mv command. It won't detect that the destination is a directory and move files into there.

You have to construct the full destination path, file by file. If you want to copy /src/a.txt to /dest/2014/, the destination path needs to be /dest/2014/a.txt.

You may want to do something like this:

File srcFile = new File("/src/a.txt");
File destDir = new File("/dest/2014");
Path src = srcFile.toPath();
Path dest = new File(destDir, srcFile.getName()).toPath(); // "/dest/2014/a.txt"
like image 26
Stuart Caie Avatar answered Oct 06 '22 01:10

Stuart Caie


Continue with @Andrew's answer

If we use only Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); then it will delete source directory because we only provide a directory path not an absolute path of a particular file. So it will also delete a source directory when operation will be done.

Let's say source path is /opt/src which contains a csv files and destination path is /opt/dst and I want to move all files from src to dst and I'm using Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); this then it will move all the files to dst but it will delete a src directory after moving all files because we didn't provide an absolute path of a each file for src as well as dst. We should have to provide src path like /opt/src/foo.csv and dst path like /opt/dst/foo.csv then and then it will not delete a source directory.

DirectoryStream used to iterate over the entries in a directory. A directory stream allows for the convenient use of the for-each construct to iterate over a directory. So we get an absolute path for src and we use resolve method for resolving an absolute path for dst.

Please refer DirectoryStream for more information.

like image 38
Deep Dalsania Avatar answered Oct 05 '22 23:10

Deep Dalsania