Created File Has No Parent?

2019-04-19 19:30发布

问题:

In a java program, I create a file with

File temp = new File("temp");
temp.createNewFile();

Then for some reason when I write

File pDir = temp.getParentFile();

and pDir is null. I actually want to write

File pDir = temp.getParentFile().getParentFile();

but that throws a null pointer exception.

回答1:

You need a file with a path for that, try getAbsoluteFile.

File pDir = temp.getAbsoluteFile().getParentFile();


回答2:

You're creating a file called temp, but it has no path, so there will be no parent path. If you want to put the file in the current directory:

File temp = new File(System.getProperty("user.dir")+"/temp");
File parent = temp.getParentFile();