开发者

Unable to create File object for a file in Jar

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 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜