This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to instantiate a file from a realtive path?  RSS feed

 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all:

I want to instantiat a file from the class path.

File file = new File("c:// .../.../.../myJar.jar");

I don't want to use the absolute file path. The jar file I am trying to instantiate is in the project class path.

I tried "../myJar.jar" and it didn't work.

Any help is greatly appreciated.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A relative path like "../MyJar.jar" has to be relative to something. If you give it to a File object constructor, it will be relative to the current user home directory which you can find in System Properties.

To make it relative to something else, use a File constructor with base path or file and relative path. To make it relative to one of the paths in the Classpath, you can get the classpath, split out all the paths in it, and try each one.

For the classpath, look in System.properties again, or maybe look in a ClassLoader. For the splitting, see String.split().

Show us what you make! If you're still stuck, at least we'll be able to see just where you're stuck.
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stan.

I found another way of solving it.

URL url = this.getClass().getResource("../myJar.jar");
File f = new File(url.toURI());
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent! What getResource() does is up to the ClassLoader implementation, but we can guess it iterates through the paths in the ClassPath until if finds your file. This is one step better than what I suggested - usually - because it works through the ClassPath of the loader that loaded "this", which might not be the same as the one in the properties, especially when running in an advanced environment like a servlet or ejb container.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!