Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

curious stuff returned in Url.getFile() or Url.getPath();

 
Phil Freihofner
Ranch Hand
Posts: 121
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to better understand what to expect when I use a .getFile() or .getPath() on a Url object. I am noticing that for resources packed in a jar, there may be an "!" in the file string separating the jar from the resource part. Also, at the beginning, there may be "file:/" preceding the "c:/Documents%20and%20Settings/Phil/..." etc. At least, this is what occurs on my Windows XP OS, from a Jar. The file string returned from within Eclipse IDE is different as well.

My understanding is that the best way to pack content files with a Jar, and then load this content, is to use the class.getResource(relativeFileName) which returns a Url or class.getResourceAsStream(relativeFileName) which returns an InputStream. Both work for my current project, but there is an object I wish to create that has a requirement for a working file name in its constructor. (I am a bit wary about going into this code--which I did not write--to try and figure out a way to redo the constructor to accept a URL.)

I can certainly do various string ops on the strings I get from .getFile(), (e.g., convert %20 to " ", strip out the "file:/" or "!") but it would be nice to know more about the range of things to expect. Or, it would be nice to know if there is a better way to determine an absolute, full path file name for a resource.

Any suggestions where I could learn more about this? I have read through the Java Tutorials "Custom Networking", "Working with URLs" section and don't see the issue addressed there.

Many thanks!
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't get a file reference for a file inside a JAR file. That's because it simply isn't an actual file anymore; it's an entry inside an existing file. I see two options here: 1) extract the file to a real file, probably using File.createTempFile to store that file in the system's temp folder, or 2) modify the library to accept an InputStream and/or URL. Converting a File into a URL is no problem; just call toURI().toURL() on the File instance.
 
Phil Freihofner
Ranch Hand
Posts: 121
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the quick, concise response, and two clear paths towards resolution. One or the other will surely work out.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic