iaacp
iaacp

Reputation: 4835

How to specify a directory when creating a File object?

This should be a really simple question but Google + my code isn't working out.

In Eclipse on Windows, I want my program to look inside a certain folder. The folder is directly inside the Project folder, on the same level as .settings, bin, src, etc. My folder is called surveys, and that's the one I want my File object to point at.

I don't want to specify the full path because I want this to run on both of my computers. Just the path immediately inside my Project.

I'm trying this code but it isn't working - names[] is coming back null. And yes I have some folders and test junk inside surveys.

File file = new File("/surveys");
    String[] names = file.list();

    for(String name : names)
    {
        if (new File("/surveys/" + name).isDirectory())
        {
            System.out.println(name);
        }
    }

I'm sure my mistake is within the String I'm passing to File, but I'm not sure what's wrong?

Upvotes: 1

Views: 125

Answers (3)

Simon Piel
Simon Piel

Reputation: 93

Make sure that your file is a directory before using file.list() on it, otherwise you will get a nasty NullPointerException.

File file = new File("surveys");
if (file.isDirectory()){
   ...
}

OR

if (names!=null){
   ...
}

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

If you checked the full path of your file with

System.out.println(file.getCanonicalPath())

the picture would immediately become clear. File.getCanonicalPath gives you exactly the full path. Note that File normalizes the path, eg on Windows "c:/file" is converted to "C:\file".

Upvotes: 0

Guido Simone
Guido Simone

Reputation: 7952

In your question you didn't specify what platform you are running on. On non-Windows, a leading slash signifies an absolute path. Best to remove the leading slash. Try this:

File file = new File("surveys");
System.out.println("user.dir=" + System.getProperty("user.dir"));
System.out.println("file is at: " + file.getCanonicalPath());
String[] names = file.list();

for(String name : names)
{
    if (new File(file, name).isDirectory())
    {
        System.out.println(name);
    }
}

Make sure the in your run configuration, the program is running from the projects directory (user.dir = <projects>)

Upvotes: 2

Related Questions