• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic