Unable to create File object for a file in Jar

亡梦爱人 提交于 2019-12-07 12:24:40

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3077317/unable-to-create-file-object-for-a-file-in-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!