Question

I am trying to copy files from one folder to another using the FileUtils method "static void copyDirectory(File srcDir, File destDir)" from apache commons io (2.4) with the following code:

String srcDir  = "/sourceDirectory/examples/";
String destDir = "/tmp/examples/";
try{
    FileUtils.copyDirectory(new File(srcDir), new File(destDir));
} catch (IOException e){
    e.printStackTrace();
}

The file structure looks like the following:

examples/                           (read access)
examples/.subdirectory              (NO access)
examples/file1.txt                  (read access)
examples/file2.txt                  (read access)
examples/subdirectory2/file1.txt    (read access)
examples/subdirectory2/file2.txt    (NO access)

The problem is, that in srcDir there are a few files and one subdirectory I don't have access to. FileUtils.copyDirectory throws an "java.io.FileNotFoundException: .subdirectory (Permission denied)" and aborts.

Is it possible to ignore those files I don't have permission to and just copy all the other files I can read?

Was it helpful?

Solution

Using a FileFilter as follow:

FileUtils.copyDirectory(new File(srcDir), new File(destDir), new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.canRead();
    }
});

See the javadoc for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top