如何真正从 Java 中的类路径读取文本文件 [英] How to really read text file from classpath in Java
问题描述
我正在尝试读取在 CLASSPATH 系统变量中设置的文本文件.不是用户变量.
I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.
我正在尝试获取文件的输入流,如下所示:
I am trying to get input stream to the file as below:
将文件目录(D:myDir
)放在CLASSPATH中,然后尝试以下操作:
Place the directory of file (D:myDir
)in CLASSPATH and try below:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
将文件的完整路径 (D:myDirSomeTextFile.txt
) 放在 CLASSPATH 中并尝试以上 3 行代码.
Place full path of file (D:myDirSomeTextFile.txt
)in CLASSPATH and try the same above 3 lines of code.
但不幸的是,它们都没有工作,我总是将 null
输入到我的 InputStream in
中.
But unfortunately NONE of them are working and I am always getting null
into my InputStream in
.
推荐答案
有了类路径上的目录,从同一个类加载器加载的类,你应该能够使用:
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
如果这些都不起作用,则表明有其他问题.
If those aren't working, that suggests something else is wrong.
例如,以下面的代码为例:
So for example, take this code:
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
还有这个目录结构:
code
dummy
Test.class
txt
SomeTextFile.txt
然后(在 Linux 机器上使用 Unix 路径分隔符):
And then (using the Unix path separator as I'm on a Linux box):
java -classpath code:txt dummy.Test
结果:
true
true
这篇关于如何真正从 Java 中的类路径读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!