SSEMember
SSEMember

Reputation: 2173

Created File Has No Parent?

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.

Upvotes: 17

Views: 6084

Answers (2)

NominSim
NominSim

Reputation: 8511

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

Upvotes: 0

J-16 SDiZ
J-16 SDiZ

Reputation: 26910

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

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

Upvotes: 44

Related Questions