Program throws NullPointerException when i try to search in drives?

后端 未结 3 1997
遥遥无期
遥遥无期 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 20:53

    This is how you fix it:

    import java.io.*;
    class FileSearch{
    static String fd;
    static boolean flg=true;
    public static void main(String arr[]){
        fd=arr[0];
        String path=arr[1];
        String dir[]=new File(path).list();
        new FileSearch().finder(dir,path);
        if(flg){System.out.print("File not found.");}
    }
    public void finder(String[] dir,String path){
        if(dir == null){
            return;
        }
        for(int i=0;i<dir.length;i++){
            if(dir[i].equals(fd)){
                System.out.println(path+"\\"+fd);
                flg=false;
            }
            if(new File(path,dir[i]).isDirectory())
                finder(new File(path,dir[i]).list(),path+"\\"+dir[i]);
        }   
    }
    }
    

    Why? String dir[]=new File(path).list(); on the directory you specified is null so when you call dir.length you will get null pointer exception

    another thing that will help you understand, System.out.print(new File(path).isDirectory()); if its false, then you will get null pointer exception.

    0 讨论(0)
  • 2021-01-05 21:05

    list()

    The documentation of listFiles() mentions that it will return null if this abstract pathname does not denote a directory, or if an I/O error occurs. Additionally, you would need to check with file.canRead() whether the application can read the directory.

    IMHO

    Always use it this way;

    String[] files = file.list();
    if (files!=null) {
        for (String f : files) processFile(f);
    }
    

    Recommend this;

    File directory = new File(directoryName);
    
    //get all the files from a directory
    File[] fList = directory.listFiles();
    
    if(fList != null){
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }
    

    Do let me know if you have any questions.

    0 讨论(0)
  • 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<Path> {
    
            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.");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题