Created File Has No Parent?

断了今生、忘了曾经 提交于 2019-12-10 02:12:18

问题


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();


来源:https://stackoverflow.com/questions/11296949/created-file-has-no-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!