Breako Breako
Breako Breako

Reputation: 6451

File exists not working when path specified

On a mac, osx, when the I do:

File file = new File("ah/myfile.text");

I can do:

file.getParent()

I get

ah

but if I do

file.exists()

I get false returned.

Why?

Upvotes: 0

Views: 875

Answers (3)

jbx
jbx

Reputation: 22128

A File does not necessary have to exist. It could be a reference to a file already on the system, or a file which can potentially be on the system.

What you are saying is that you have a path to a (potential) file at ah/myfile.text, but it could be that neither the file nor the parent directory exists yet. Its parent is still ah/ though.

You can also check if the parent exists by doing file.getParentFile().exists();

Upvotes: 0

AlexR
AlexR

Reputation: 115328

getParent () just parses given path and removes the last section aftwr last slash. However exists () performs a real check. I gess that yor file indeed does not exist in this location. To check your current directory do new File(".").getAbsolutePath () and modify your path accordingly.

Upvotes: 2

JBuenoJr
JBuenoJr

Reputation: 975

File file = new File("ah/myfile.text");

System.out.println(file.getParent());
System.out.println(file.exists());

Output:

ah
false

I get the same result. Get parent must parse the path as a string, even if it the file and/or the directory does not exist.

Upvotes: 0

Related Questions