0

I am new to this group. Please suggest how to return File[] array as my code below is giving NullPointerException when I am trying to add all text files from "D:\" to File[] array, as I want to return all text files as an File[] array which will be used in another method to read all text files.

File[] allFiles;

int i = 0;

public File[] findFiles(File source) {

    FileFilter filter = new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            // TODO Auto-generated method stub
            if (!pathname.isHidden()) {
                return true;
            }
            return false;
        }
    };

    File[] list = source.listFiles(filter);
    if (list != null) {
        for (File f : list) {
            if (f.isDirectory()) {
                findFiles(f);
            }
            if (f.getName().contains("txt")) {
                System.out.println(f.getAbsolutePath());

                allFiles[i] = f; // it is giving nullpointerexception
                i++;
            }

        }
    }

    return allFiles; // want to return this to another method
}
0

4 Answers 4

1

The main problem you're having is you've not initialized allFiles before using it...

File[] list = source.listFiles(filter);
if (list != null) {
    for (File f : list) {
            //...
            // still null
            allFiles[i] = f; // it is giving nullpointerexception

You could use allFiles = new File[list.length], but the problem here is you could end up with null elements in the list, as you are filtering out elements...

Instead, you could use your FileFilter, that's what it's there for...for example...

public File[] findFiles(File source) {

    FileFilter filter = new FileFilter() {

        @Override
        public boolean accept(File pathname) {

            return !pathname.isHidden() && 
                   pathname.getName().toLowerCase().endsWith(".txt");

        }
    };

    File[] list = source.listFiles(filter);

    return list;
}

Basically, what this does is checks to see if the file is not hidden and if its name ends with .txt, as an example...

Updated

Because you're doing a recursive look up, you really need some way to add new files to your array and grow it dynamically.

While you can do this with plain old arrays, some kind of List would be much easier, for example...

The following uses the FileFilter to find all non-hidden files that directories or end in .txt

It then sorts the resulting list of files, so that the "files" appear first and the "directories" or sorted to the bottom, this is a nit pick, but ensure a certain order of files in the list.

It then processes the file list, adding the "files" to the List and recurisivly scanning the "directories", adding the results to the List...

public static File[] findFiles(File source) {

    FileFilter filter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return !pathname.isHidden() && 
                    (pathname.isDirectory() || 
                    pathname.getName().toLowerCase().endsWith(".txt"));
        }
    };

    File[] files = source.listFiles(filter);
    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            int compare = 0;
            if (o1.isDirectory() && o2.isDirectory()) {
                compare = 0;
            } else if (o1.isFile()) {
                compare = -1;
            } else {
                compare = 1;
            }
            return compare;
        }
    });

    List<File> fileList = new ArrayList<>(25);
    for (File file : files) {
        if (file.isFile()) {
            fileList.add(file);
        } else {
            fileList.addAll(Arrays.asList(findFiles(file)));
        }
    }

    return fileList.toArray(new File[fileList.size()]);
}

As an example...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot:) why I dint notice that :(
0

Very simple, just initialize the allFiles array

File[] list = source.listFiles(filter);

// initialize here because we know the size now.
allFiles = new File[list.length];

Comments

0

Define the File[] allFiles,Like -

File[] allFiles = new File[list.length];

Alternatively you can use List instead of Array, which is dynamic array(not fixed size).

Initialization -

List<File> allFiles = new ArrayList<File>();

Adding element -

allFiles.add(f);

Comments

0
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
  return !pathname.isHidden() &&  
         pathname.getName().toLowerCase().endsWith(".txt");
    }
};

File[] files = f.listFiles(filter);
for (File file : files) {
    if (file.isDirectory()) {
        System.out.print("is a directory");
    } else {
        System.out.print("is a file");
    }
    System.out.println(file.getCanonicalPath());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.