无法为Jar中的文件创建File对象 [英] Unable to create File object for a file in Jar

查看:262
本文介绍了无法为Jar中的文件创建File对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些文本文件作为资源包含在我的runnable .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();

导出为可运行的jar后,运行时得到以下输出:

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


打开URI:rsrc:etc / inputfile.txt

java.lang.IllegalArgumentException:URI不是java的分层
。 io.File。(File.java:363)

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

如果我使用getResourceAsStream,文件可以毫无问题地打印,但我' d出于其他原因想使用File对象。

如何解决这个问题?

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?

谢谢,

Martin

Thanks,
Martin

推荐答案

只有当方案为文件时,URI才代表文件:
和构造函数文件(URI)在此清楚。
您不能将jar中的打包文件视为File,因为......它不是Java认为的文件:读取定义 File类代表的内容

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:


文件和
目录路径名的抽象表示

正如你所说,读取的方式是 getResourceAsStream()

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

这篇关于无法为Jar中的文件创建File对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆