| Author |
File vs InputStream when getting a reference to file under the class path
|
kartik krishnan
Ranch Hand
Joined: Nov 19, 2006
Posts: 63
|
|
Hi, I have a file Sample.txt directly under my classpath. When I try to do File file = new File("Sample.txt"); System.out.println(file.exists()) returns false; But ClassLoader.getSystemResourceAsStream("Sample.txt") != null returns true. Have I have done anything wrong? Please help?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
The File constructor creates a file relative to the local path - where you started the JVM. Therefore, the file could only exist if the Sample.txt was in the current folder. ClassLoader.getSystemResource(AsStream) loads a resource relative to the classpath. That can include folders not inside the current folder. This is apparently the case.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
If you're trying to figure out where the system is looking for Sample.txt, try or Or if you can find Sample.txt as a resource, but want it as a File, you can use
|
"I'm not back." - Bill Harding, Twister
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
Originally posted by Jim Yingst: Or if you can find Sample.txt as a resource, but want it as a File, you can use
Note that this doesn't work for all resources (if it does work at all?). The URL could easily point inside a jar-file, or be a HTTP URL (for example in the case of Webstart). Those resources cannot be represented as a File object.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
True, as long as I was checking for url != null I should have also verified that: [ May 09, 2008: Message edited by: Jim Yingst ]
|
 |
 |
|
|
subject: File vs InputStream when getting a reference to file under the class path
|
|
|