getResource()在运行时到文件 [英] getResource() to a file at runtime
问题描述
我在 src
文件夹下放了一些 .txt
文件(在资源<中/ code>文件夹)。
I put some .txt
files under the src
folder (in the resources
folder).
但我无法在运行时创建有效的文件
资源。
But I can't create a valid File
at runtime from this resource.
String path = this.getClass().getResource("/resources/file.txt").getFile();
File file = new File(path);
if (!file.exists()) {
}
我从eclipse运行我的程序。我没有在classpath中添加任何内容。
我想将我的文本文件嵌入到 .jar
文件中,当我运行我想要的应用程序时抓住这些文件并将其复制到某个位置。
I run my program from eclipse. I didn't put in classpath anything.
I want my text files to be embedded into the .jar
file, when I run my app I want to grab those files and copy them into some location.
更新
如果我做 InputStream is = getClass()。getResourceAsStream(/ resources / file.txt);
I得到流!!
推荐答案
正如您在发布问题后不久发现的那样,这有效:
As you already discovered yourself soon after posting your question, this works:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
原因这是有效的,而原始代码没有,是因为zip文件中的文件(jar文件是zip文件)在提取之前不是真正的文件。但是提取文件是你想要做的,所以在你的程序中,它不是一个真正的文件。所以这个问题是 XY问题:你想创建一个File对象,但那是不可能的 - 你需要回顾一下你最初尝试做的事情,这是从zip条目中读取的。
The reason this works, while your original code doesn't, is because a "file" inside in a zip file (a jar file is a zip file) is not a real file until it has been extracted. But extracting the file is what you are trying to do, so at that point in your program, it's not a real file. So this question is an X-Y problem: you wanted to create a File object, but that wasn't possible - you needed to refer back to what you were originally trying to do, which was read from the zip entry.
这篇关于getResource()在运行时到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!