views:

48

answers:

2

Hi,

I am trying to include a number of text files as resources in my runnable .jar-file. The following code should print the contents of one file:

URI resourceFile = Driver.class.getResource("/etc/inputfile.txt").toURI();
System.out.println("Opening URI: " + resourceFile.toString());
File infile = new File(resourceFile);

Scanner sc = new Scanner(infile);
while (sc.hasNextLine())
    System.out.println(sc.nextLine());
sc.close();

After exporting as a runnable jar, I get the following output when running:

Opening URI: rsrc:etc/inputfile.txt
java.lang.IllegalArgumentException: URI is not hierarchical at java.io.File.(File.java:363)

The file can be printed without any problems if I use getResourceAsStream, but I'd like to use the File object for other reasons.
How can I resolve this?

Thanks,
Martin

A: 

A URI represents a "file" only when the scheme is file:. And the constructor File(URI) is clear on this. You can't treat a packed file inside a jar as a File because... it just isn't what Java considers a File: read the definition of what the File class represents:

An abstract representation of file and directory pathnames.

The way to read is by getResourceAsStream(), as you said.

leonbloy
OK, thanks. Do you know of any open source framework that helps abstract this so I can treat files and jar streams alike?
Martin Wiboe
I use `URL` (or URI) for this. It can be consider as a generalization that includes files (scheme `file:`) and resources inside jars (scheme `jar:` ) as special cases. But remember: a java `File` is conceptually just the path, think of it as the name of the file. It's the identifier of a resource (which is not necessarily opened, which perhaps even does not exist). Don't mix that concept with the content of the file. A stream is a content.
leonbloy
A: 

You can't. java.io.File is an abstraction over paths and pathnames on a filesystem. You will need to stick in the URL domain if you want to reference files inside a JAR.

dty