I am trying to use the getParent method of the File library. Here is the code I am working with, but I am getting a null string:

public class MyCode {
    public static void main (String[] args) {
    File f = new File("");
    String name = f.getParent();
    System.out.println(name);
    }
}

This code prints "null" to the terminal. I am very confused.

Recommended Answers

All 3 Replies

Your File object does not refer to any actual file (the file name is a zero length string) so it has not got a parent.

That is correct, but when I do an f.getAbsolutePath();, I get the current directory. Should I be doing something like:

File f = new File(System.getProperties("user.dir"));

That depends on what you are trying to achieve!
If you want the current user directory then Sytem.getProperty is the right answer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.