使用Java NIO将文件从一个目录移动到另一个目录

时间:2014-03-12 15:41:57

标签: java io directory nio

我正在使用NIO库但是当我尝试将文件从一个目录移动到另一个目录时,我收到一个奇怪的错误。

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
     }
}

迭代以“2014”开头的元素并将它们移动到新目录中(newDir,也称为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
}

我得到了java.nio.file.FileAlreadyExistsException,因为我的文件夹(2014)已经存在。我真正想做的是将所有以“2014”开头的文件移到2014年目录中。

4 个答案:

答案 0 :(得分:10)

Files.move不等同于mv命令。它不会检测到目标是一个目录并将文件移动到那里。

您必须逐个文件地构建完整的目标路径。如果您要将/src/a.txt复制到/dest/2014/,则目标路径必须为/dest/2014/a.txt

您可能想要这样做:

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"

答案 1 :(得分:9)

最好不要回到java.io.File并改为使用NIO:

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

答案 2 :(得分:0)

尝试此代码:

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

答案 3 :(得分:-1)

使用java.io.File,就像这样简单:

File srcFile = new File(srcDir, fileName);
srcFile.renameTo(new File(destDir, "a.txt"));