getResource()到运行时的文件 [英] getResource() to a file on runtime
问题描述
我在src包(int resources文件夹)下放了一些txt文件。
I put some txt files under src package (int resources folder).
但是我无法在运行时从这个资源创建一个文件。
But I can't create a file on runtime from this resource.
String path = this.getClass().getResource("/resources/file.txt").getFile();
File file = new File(path );
if (!file.exists()) {
}
UPDATE
如果我做 InputStream is = getClass()。getResourceAsStream(/ resources / file.txt );
我得到了流!!
我运行我的程序来自日食。我没有在classpath中添加任何内容。
我希望我的文本文件嵌入到jar中,当我运行我的应用程序时,我想抓住这些文件并将它们复制到某个位置。
I run my program from eclipse. I didn't put in classpath anything.
I want my text files to be embedded into jar, when i run my app i want to grab those files and copy them into some location.
推荐答案
你说你正在使用eclipse,并且你将文本文件拖放到src包中。 src不是包。它只是一个文件系统目录。默认情况下,在eclipse中的Java项目中,所有源代码都存储在名为src的目录中,所有.class文件都存储在名为bin的目录中。 getClass()。getResource()解析为.class文件的位置。您必须将文本文件移动到bin目录中。
You said that you are using eclipse, and that you dragged and dropped your text files into the "src" package. "src" is not a package. It is simply a file system directory. By default in a Java project in eclipse all your source code is stored in a directory called "src" and all your .class files are stored in a directory called "bin". getClass().getResource() resolves to the location of your .class files. You must move the text files into the "bin" directory.
您的班级是哪个套餐?
我在默认包中写了非常相似的代码并在eclipse中运行。
I wrote very similar code to yours in the default package and ran it in eclipse.
import java.io.File;
public class ResourceTest {
public static void main(String[] args) {
ResourceTest rt = new ResourceTest();
rt.openFile();
}
public void openFile() {
String path = this.getClass().getResource("/resources/file.txt").getFile();
File file = new File(path);
System.out.println(path);
System.out.println(file.getAbsolutePath());
System.out.println(file.exists());
}
}
我看到这个输出:
/C:/Users/rab29/Documents/eclipse/Overflow/bin/resources/file.txt
C:\Users\rab29\Documents\eclipse\Overflow\bin\resources\file.txt
true
这篇关于getResource()到运行时的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!