Unable to copy files using FileUtils

Maddy picture Maddy · Dec 15, 2016 · Viewed 15k times · Source

I am trying to copy the files from one destination to another. I am unable to understand why the error occurs. Any help is appreciated.

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

I get the following error Exception in thread "main" java.io.IOException: Destination 'C:\Users\username\Desktop\ZipFiles' exists but is a directory

Answer

Haifeng Zhang picture Haifeng Zhang · Dec 15, 2016
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);

Try copyFileToDirectory(srcFile, destDir), you have to provide the source file absolute path with the file name, and the absolute path to the destination directory.

In addition, make sure you have write permission to copy the file to the destination. I am always on Linux system don't know how to achieve that, similarly you should be have Administrator privilege on Windows or some similar roles which is able to write files.