Created File Has No Parent?

2019-04-19 19:50发布

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.

2条回答
2楼-- · 2019-04-19 20:00

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();
查看更多
祖国的老花朵
3楼-- · 2019-04-19 20:11

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

File pDir = temp.getAbsoluteFile().getParentFile();
查看更多
登录 后发表回答