Question

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.

Était-ce utile?

La solution 2

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"

Autres conseils

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();
    }

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.

Try this code:

public class App
{
    public void moveFromSourceToDestination(String sourceName,String destinationName)
    {
        File mydir = new File(sourceName);
        if (mydir.isDirectory())
        {
            File[] myContent = mydir.listFiles();
            for(int i = 0; i < myContent.length; i++)
            {
                File file1 = myContent[i];
                file1.renameTo(new File(destinationName+file1.getName()));
            }
        }
    }

    public static void main(String [] args)
    {
        App app = new App();
        String sourceName = "C:\\Users\\SourceFolder";
        String destinationName = "C:\\Users\\DestinationFolder\\";
        app.moveFromSourceToDestination(sourceName,destinationName);
    }
}

Using java.io.File, its as simple as this:

File srcFile = new File(srcDir, fileName);
srcFile.renameTo(new File(destDir, "a.txt"));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top