无法使用 FileUtils 复制文件

Unable to copy files using FileUtils

我正在尝试将文件从一个目的地复制到另一个目的地。我无法理解为什么会发生错误。感谢任何帮助。

public class FileSearch {

    public void findFiles(File root) throws IOException {

        File[] listOfFiles = root.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            String iName = listOfFiles[i].getName();
            if (listOfFiles[i].isFile() && iName.endsWith(".tif")) {
                long fileSize = listOfFiles[i].length();

                long sizeToKb = fileSize/1024;

                File copyDest = new File("C:\Users\username\Desktop\ZipFiles");

                if (fileSize <= 600000) {
                    System.out.println("|" + listOfFiles[i].getName().toString() + " | Size: " + sizeToKb+" KB");
                    FileUtils.copyFile(listOfFiles[i], copyDest);
                }

            } else if (listOfFiles[i].isDirectory()) {
                findFiles(listOfFiles[i]);
            }
        }
    }

我收到以下错误Exception in thread "main" java.io.IOException: Destination 'C:\Users\username\Desktop\ZipFiles' exists but is a directory

你想要FileUtils.copyFileToDirectory(srcFile, destDir)

为什么会出现这个错误? FileUtils.copyFile 用于将文件复制到新位置。来自文档:

This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.

此处,目标存在,但不是文件;相反,它是一个目录。您不能用 文件 的内容覆盖 目录

File srcFile = new File("/path/to/src/file.txt");  // path + filename     
File destDir = new File("/path/to/dest/directory"); // path only
FileUtils.copyFileToDirectory(srcFile, destDir);

试试copyFileToDirectory(srcFile, destDir),你必须提供源文件的绝对路径和文件名,以及目标目录的绝对路径。

此外,请确保您具有将文件复制到目标位置的写入权限。我总是在 Linux 系统上不知道如何实现这一点,同样你应该对 Windows 或一些能够写入文件的类似角色具有管理员权限。