• Post Reply Bookmark Topic Watch Topic
  • New Topic

File vs InputStream when getting a reference to file under the class path  RSS feed

 
kartik krishnan
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True, as long as I was checking for url != null I should have also verified that:

[ May 09, 2008: Message edited by: Jim Yingst ]
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!