Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.io.File.exists() returns false, when the file is actually existing

 
Kumar Raja
Ranch Hand
Posts: 547
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

I'm stuck with a basic issue related to File I/O operations. I have the below code as

My project structure is as follows

C:\Workspace\LearnJava\src\org\learning\java\MyFiler.java
C:\Workspace\LearnJava\src\resources\sample.properties



and the output is



As you see, the first two methods return me the absolutePath and canonicalPath, but the absolutePath is actually "C:\Workspace\LearnJava\src\resources\sample.properties" , "src" is missing in the output.

But the real question is, when getAbsolutePath() returns me an output, whether correct or not, why the other methods returning me false. If exists() is returning false, that means it could not find the file, but then it should not return the absolutePath() also.

If I change the resource folder to the LearnJava folder level instead of src level, then the output is

C:\Workspace\LearnJava\resources\sample.properties
C:\Workspace\LearnJava\resources\sample.properties
false
true
true
true
true

What is the mistake I'm doing here ?
 
Nam Ha Minh
Ranch Hand
Posts: 502
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that your program's working directory is:

C:\Workspace\LearnJava

whereas you thought that it is C:\Workspace\LearnJava\src.
 
Kumar Raja
Ranch Hand
Posts: 547
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with you on the path of the file.

But why would f.getAbsolutePath(); return me some value (may not be correct) at first place, while f.exists() is failing
 
Nam Ha Minh
Ranch Hand
Posts: 502
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you specify the wrong path then the file does not exist. The getAbsolutePath() method returns the path you specified, it doesn't necessarily return an existing path.
 
Kumar Raja
Ranch Hand
Posts: 547
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Nam Ha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic