I am trying to search my hard drive for mp4 files and copy them into a specific folder. The problem is that I don't have permission to access folders like: "C:\Documents and Settings"
, so my program stops when it encounters those rather than continuing on.
I tried to create a blacklist but it don't work at all.
package S;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class C {
public static void main(String args[]) throws IOException {
Path dir = Paths.get("C:/");
Files.walkFileTree(dir, new FindJavaVisitor());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().contains(".mp4")) {
file.toFile().renameTo(new File("C:/MP4/"+file.toFile().getName()));
}
return FileVisitResult.CONTINUE;
}
}
}
You have to override two methods.
The first is the
visitFileFailed()
method.As the documentation states:
You also have to override the
postVisitDirectory()
method; it has two arguments, the second being anIOException
. If there is an error, the second argument will not be null and in this case, from the documentation again:Given your error, the second one is the one you want to override.
However, I see in your code that you do
file.toFile().renameTo()
.Do not use this. Use
Files.move()
instead.Finally, you also move while you are iterating... this is not a very good idea. Recall that the list of files in a directory, for instance, and unlike with the old API, is dynamically populated!
You should create a "renaming"
Map<Path, Path>
and perform the renames after you have visited it all. At least that is how I would proceed in this case.