File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading a file which is specified in CLASSPATH

 
Pranav Pal
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We generally give the filepath like:
File file = new File(filepath);

But now if my filepath is stored in CLASSPATH environment variable, then how can I access this filepath in my program using CLASSPATH variable or by some another mechanism and not specifying the absolute or relative path to the file?
 
Jan Cumps
Bartender
Posts: 2574
11
C++ Linux Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class.getResourceAsStream() allows you to read files in the classpath.
 
Rajesh Narkhed
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will need to read the CLASSPATH env variable as

String claspathValue = System.getProperty("java.class.path"));

and then parse the value of claspathValue String to fetch the location of file that you want.
 
Jan Cumps
Bartender
Posts: 2574
11
C++ Linux Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rajesh Narkhed:
You will need to read the CLASSPATH env variable...
and then parse the value of claspathValue String to fetch the location of file that you want.
How would that work? A classpath contains several entries, pointing either to jars or to directories. How can you parse and fetch a file location from that?

Regards, Jan
 
Rob Spoor
Sheriff
Pie
Posts: 20368
43
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jan Cumps:
Class.getResourceAsStream() allows you to read files in the classpath.

But you need the reference to be relative to some class, or absolute for some class loader. How do you know which class?

Originally posted by Jan Cumps:
How would that work? A classpath contains several entries, pointing either to jars or to directories. How can you parse and fetch a file location from that?

Regards, Jan

Split on File.separator*, convert each element to a File object and check that.

* This works in all cases except if a file contains File.separator. Which it cannot on most OSes.
 
Jan Cumps
Bartender
Posts: 2574
11
C++ Linux Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you need the reference to be relative to some class, or absolute for some class loader. How do you know which class?
As long as the file is in a directory that is listed in the classpath, you can load it by simply using the filename as parameter.

Regards, Jan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic