Mihai Bratulescu
Mihai Bratulescu

Reputation: 1945

Error getting file tree

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileTree {
    List<File> file_list = new ArrayList<File>();

    public List<File> getTree(String root)
    {
        File f = new File(root);
        ArrayList<File> tmp = new ArrayList<File>(Arrays.asList(f.listFiles()));

        for(int i = 0; i < tmp.size(); i++)
        {
            f = tmp.get(i);
            if(f.isFile())
                file_list.add(f);
            else if(f.isDirectory()) 
                getTree(root + "\\" + f.getName());
        }

        return file_list;
    }
}

Error:

  Exception in thread "main" java.lang.NullPointerException
        at java.util.Arrays$ArrayList.<init>(Arrays.java:2842)
        at java.util.Arrays.asList(Arrays.java:2828)
        at FileTree.getTree(FileTree.java:12)
        at FileTree.getTree(FileTree.java:22)
        at Server.main(Server.java:10)

I'm trying to get a list of files from a directory (root). The code was working until I tried to access subfoders. What is the problem here?

Upvotes: 0

Views: 106

Answers (2)

enterbios
enterbios

Reputation: 1755

Form a listFiles of java.io.File documentation:

Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

I see you're checking if file actually is directory, despite first call on root. What might cause your problem then are I/O errors like permission denied for example. Also the way how you create root path string might cause problems on different file systems, try changing this line

getTree(root + "\\" + f.getName());

into

getTree(f.getAbsolutePath());

Upvotes: 0

Meno Hochschild
Meno Hochschild

Reputation: 44071

The method File#listFiles() yields null if the file object (f) does not denote a directory (or if an I/O-error occurs).

So before you call f.listFiles() you should first check if f represents a directory - your input root might not be directory. You can use this method: File#isDirectory() and then adjust your logic. Or: You have not got granted access privileges for one given subdirectory. In this case you might check readability by using the method canRead() (and don't forget to debug f.getName() and then to find out if you have enough access rights).

Upvotes: 2

Related Questions