如何在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:
放置在CLASSPATH中的文件目录( D:\ myDir
)并尝试以下内容:
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:\ myDir \ SomeTextFile。 CLASSPATH中的txt
)并尝试上面3行代码。
Place full path of file (D:\myDir\SomeTextFile.txt
)in CLASSPATH and try the same above 3 lines of code.
但不幸的是,他们中的任何一个都在工作,我总是得到 null
进入我的InputStream
。
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
然后(使用Unix路径分隔符,因为我在Linux机器上):
And then (using the Unix path separator as I'm on a Linux box):
java -classpath code:txt dummy.Test
结果:
true
true
这篇关于如何在Java中从类路径中真正读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!