如何从Java中的classpath中真正读取文本文件

问题:

我正在尝试读取在CLASSPATH系统变量中设置的文本文件。不是用户变量。
我正在尝试获取输入流到文件如下:
将文件(D:\myDir)的目录放在CLASSPATH中,然后尝试:

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.txt)的完整路径放在CLASSPATH中,并在3行代码上尝试相同的操作。
但不幸的是,他们中的任何一个都在工作,我总是将null加入到我的InputStream in

回答:

使用类路径上的目录,从同一个类加载器加载的类中,您应该可以使用以下任一种:

// 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");

如果这些不起作用,这表明有别的事情是错误的。
所以例如,采取以下代码:

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框上):

java -classpath code:txt dummy.Test

结果:

true
true

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to really read text file from classpath in Java

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

4 + 5 =