首页 > 解决方案 > 使用 Files.move 创建新的“文件”文件类型,而不是将文件移动到目录

问题描述

我正在尝试制作一个程序,从那里的单个文件夹中提取多个 MP4 文件并将它们放在已经创建的文件夹中(代码已稍作更改,因此它不会再弄乱任何 MP4,而是虚拟文本文件)。

我已经设法列出了指定文件夹中的所有文件夹/文件,但是在将它们移动到目录时遇到了麻烦。

static File dir = new File("G:\\New Folder");
static Path source;
static Path target = Paths.get("G:\\gohere");

static void showFiles(File files[]) {
    for (File file : files) { // Loops through each file in the specified directory in "dir" variable.

        if (file.isDirectory()) { // If the file is a directory.

            File[] subDir = file.listFiles(); // Store each file in a File list.

            for (File subFiles : subDir) { // Loops through the files in the sub-directory.
                if (subFiles.getName().endsWith(".mp4")) { // if the file is of type MP4
                    source = subFiles.toPath(); // Set source to be the abs path to the file.
                    System.out.println(source);
                    try {
                        Files.move(source, target);
                        System.out.println("File Moved");
                    } catch (IOException e) {
                        e.getMessage();
                    }
                }
            }
        } else {
            source = file.toPath(); // abs path to file
            try {
                Files.move(source, target);
                System.out.println("File moved - " + file.getName());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[] args) {
    showFiles(dir.listFiles());
}

问题是当我将文件从源文件夹移动到目标时,它会删除或转换目标。

截屏

标签: javanio

解决方案


Files.move不像命令行。你在编程。你必须把事情说清楚。您实际上是在要求Files.move这样做,以便target(这里, G:\GoHere) 从此成为您要移动的文件的位置。如果您打算:不,目标是G:\GoHere\TheSameFileName您必须对此进行编程。

另外,您的代码一团糟。停止使用java.io.Filejava.nio.Path一起。选择一方(选择java.nio一方,这是一个新的 API 有充分的理由),不要混搭。

例如:

Path fromDir = Paths.get("G:\\FromHere");
Path targetDir = Paths.get(G:\\ToHere");
try (DirectoryStream ds = Files.newDirectoryStream(fromDir)) {
  for (Path child : ds) {
    if (Files.isRegularFile(child)) {
      Path targetFile = targetDir.resolve(child.getFileName());
      Files.move(child, targetFile);
    }
  }
}

resolve给你一个Path你在这里需要的对象:目标目录中的实际文件。


推荐阅读