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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22356585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:11:50  来源:igfitidea点击:

Moving files from one directory to another with Java NIO

javaiodirectorynio

提问by Gregg1989

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

我正在使用 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
     }
}

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

迭代以“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
}

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.

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

采纳答案by Stuart Caie

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

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

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

您必须逐个文件地构建完整的目标路径。如果要复制/src/a.txt/dest/2014/,目标路径需要是/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"

回答by Andrew

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

最好不要回到 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();
    }

回答by Jaydev

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

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

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

回答by Abdullah

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