在Java中使用C驱动器搜索文件时出错

时间:2014-08-15 15:02:51

标签: java hibernate search

我想编写一个Java程序,它将在我的C:\驱动器中搜索特定文件。

这是我的代码:

public class Hibernate 
{
    public static void main(String[] args) throws IOException 
    {
        String directory = "C:\\"; 
        Path start = FileSystems.getDefault().getPath(directory);
        Files.walkFileTree(start, new SimpleFileVisitor<Path>(){ 
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException 
            {
                if (file.toString().contains("hiberfil.sys")) 
                {
                    System.out.println(file);
                }
                else
                {
                    System.out.println("No such file!");
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

现在的问题是,当我运行它时,它会给我以下错误:

No such file!
Exception in thread "main" java.nio.file.AccessDeniedException: C:\$Recycle.Bin\S-1-5-20
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsDirectoryStream.<init>(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream(Unknown Source)
    at java.nio.file.Files.newDirectoryStream(Unknown Source)
    at java.nio.file.FileTreeWalker.walk(Unknown Source)
    at java.nio.file.FileTreeWalker.walk(Unknown Source)
    at java.nio.file.FileTreeWalker.walk(Unknown Source)
    at java.nio.file.FileTreeWalker.walk(Unknown Source)
    at java.nio.file.Files.walkFileTree(Unknown Source)
    at java.nio.file.Files.walkFileTree(Unknown Source)
    at Hibernate.main(Hibernate.java:43)

但是,当我将String directory = "C:\\";更改为String directory = "F:\\";(我的拇指驱动器)时,它会给我带来很多No such file!,但没有如上所示的错误。

但根据错误:Hibernate.java:43应为:Files.walkFileTree(start, new SimpleFileVisitor<Path>(){

我该如何解决这个问题?任何帮助将不胜感激!!!

1 个答案:

答案 0 :(得分:1)

请覆盖用于跳过无法访问的文件的visitFileFailed方法。

public class Hibernate {
    public static void main(String[] args) throws Exception {
        String directory = "c:\\";

        Path start = FileSystems.getDefault().getPath(directory);
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {

                if (file.toString().contains("hiberfil.sys")) 
                    System.out.println(file);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exp) {
                // System.out.println(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}