Program throws NullPointerException when i try to search in drives?

后端 未结 3 2036
遥遥无期
遥遥无期 2021-01-05 20:24

I wrote a program to find file or directory.
Its working properly when i am trying to Search file with in Directory
example
java FileSea

3条回答
  •  独厮守ぢ
    2021-01-05 21:13

    Another alternative is to using the FileVisitor interface introduced in JDK7 to perform the search. The link at http://docs.oracle.com/javase/tutorial/essential/io/walk.html provides details on how to use the FileVisitor interface.

    The following code block is a re implementation of the search that should be able to list files at a windows drive level in addition to normal directories. Note that the implementation uses Files.walkTree method that is provided as part of the NIO 2 File IO Operations.

    public class FileSearch {
        static String fd;
        static boolean flg = true;
    
        static class FileSearchVisitor extends SimpleFileVisitor {
    
            private final Path pathToSearch;
    
            boolean found;
    
            FileSearchVisitor(Path pathToSearch) {
                found = false;
                this.pathToSearch = pathToSearch;
            }
    
            public boolean isFound() {
                return found;
            }
    
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                super.preVisitDirectory(dir, attrs);
                if (pathToSearch.getFileName().equals(dir.getFileName())) {
                    System.out.println("Found " + pathToSearch);
                    found = true;
                }
                return FileVisitResult.CONTINUE;
            }
    
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                super.visitFile(file, attrs);
                if (pathToSearch.getFileName().equals(file.getFileName())) {
                    System.out.println("Found " + pathToSearch);
                    found = true;
                }
                return FileVisitResult.CONTINUE;
            }
    
            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) {
                System.err.println("Visit failed for file at path : " + file);
                exc.printStackTrace();
                return FileVisitResult.CONTINUE;
            }
    
        }
    
        public static void main(String arr[]) throws Exception {
            fd = arr[0];
            String path = arr[1];
    
            final Path searchFile = Paths.get(fd);
            Path filePath = Paths.get(path);
            FileSearchVisitor visitor = new FileSearchVisitor(searchFile);
            Files.walkFileTree(filePath, visitor);
            if (!visitor.isFound()) {
                System.out.print("File not found.");
            }
        }
    }
    

提交回复
热议问题