getResource() 在运行时到文件 [英] getResource() to a file at runtime

查看:22
本文介绍了getResource() 在运行时到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些 .txt 文件放在 src 文件夹下(在 resources 文件夹中).

I put some .txt files under the src folder (in the resources folder).

但我无法在运行时从此资源创建有效的 File.

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 运行我的程序.我没有在类路径中放入任何东西.
我希望我的文本文件被嵌入到 .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");

我收到了直播!!

推荐答案

正如您在发布问题后不久就发现自己的那样,这是有效的:

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屋!

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