3

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

Martin Wiboe
  • 1,960
  • 2
  • 25
  • 45
  • 1
    Dupe of http://stackoverflow.com/questions/676097/java-resource-as-file or http://stackoverflow.com/questions/403256/how-do-i-read-a-resource-file-from-a-java-jar-file – Romain Hippeau Jun 19 '10 at 22:26
  • https://stackoverflow.com/questions/46135427/uri-not-hierarchical-need-to-use-file-class-for-a-method/46135584?noredirect=1#comment79233689_46135584 may possibly help. I had similar problem. – shadowforce100 Sep 09 '17 at 23:21

2 Answers2

8

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
  • 65,169
  • 19
  • 130
  • 176
  • 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 Jun 19 '10 at 22:22
  • 2
    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 Jun 19 '10 at 22:29
1

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
  • 18,132
  • 6
  • 51
  • 78