Maddy
Maddy

Reputation: 2060

Unable to copy files using FileUtils

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

Upvotes: 3

Views: 21990

Answers (2)

Haifeng Zhang
Haifeng Zhang

Reputation: 31885

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.

Upvotes: 17

AJNeufeld
AJNeufeld

Reputation: 8695

You want FileUtils.copyFileToDirectory(srcFile, destDir)

Why does the error occur? FileUtils.copyFile is used to copy a file to a new location. From the documentation:

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.

Here, the destination exists, but is not a file; rather it is a directory. You cannot overwrite a directory with the contents of a file.

Upvotes: 5

Related Questions