Question

I wrote a program to find file or directory.
Its working properly when i am trying to Search file with in Directory
example
java FileSearch abc.txt f:\xyz
But when i am try to search file from local drive than program throw Exception
java FileSearch abc.txt f:\
after Showing all the search result throws NullPointerException.

nullpointerexcepion

code is :

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){
    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]);
    }   
}
}

I want to know why this exception is thrown and how can i fix it.

Was it helpful?

Solution

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.

OTHER TIPS

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.");
        }
    }
}

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.

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