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

在Java中从classpath读取文本文件时,必须使用正确的类加载器。尝试将文件目录或完整路径置于CLASSPATH中,然后通过类加载器获取InputStream。如果不起作用,可能是系统变量设置的问题,确保在新控制台中启动Java程序或使用启动脚本来设置类路径。另外,Spring Framework提供Resource接口方便读取资源。
摘要由CSDN通过智能技术生成

本文翻译自:How to really read text file from classpath in Java

I am trying to read a text file which is set in CLASSPATH system variable. 我正在尝试读取在CLASSPATH系统变量中设置的文本文件。 Not a user variable. 不是用户变量。

I am trying to get input stream to the file as below: 我试图获取输入流到文件,如下所示:

Place the directory of file ( D:\\myDir )in CLASSPATH and try below: 将文件目录( 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");

Place full path of file ( D:\\myDir\\SomeTextFile.txt )in CLASSPATH and try the same above 3 lines of code. 在CLASSPATH中放置文件的完整路径( D:\\myDir\\SomeTextFile.txt )并尝试相同的上述3行代码。

But unfortunately NONE of them are working and I am always getting null into my InputStream in . 但遗憾的是,他们中的任何一个都在工作,我总是在我的InputStream in null


#1楼

参考:https://stackoom.com/question/68vb/如何在Java中从classpath中真正读取文本文件


#2楼

Please try 请试试

InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

Your tries didn't work because only the class loader for your classes is able to load from the classpath. 您尝试没有成功,因为只有你的类的类加载器能够从classpath加载。 You used the class loader for the java system itself. 您使用了类加载器来为java系统本身。


#3楼

你必须把你的'系统变量'放在java类路径上。


#4楼

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);
    }
}

And this directory structure: 而这个目录结构:

code
    dummy
          Test.class
txt
    SomeTextFile.txt

And then (using the Unix path separator as I'm on a Linux box): 然后(使用Unix路径分隔符,因为我在Linux机器上):

java -classpath code:txt dummy.Test

Results: 结果:

true
true

#5楼

When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction. 使用Spring Framework时(无论是作为实用程序容器的集合 - 您不需要使用后者的功能),您都可以轻松使用Resource抽象。

Resource resource = new ClassPathResource("com/example/Foo.class");

Through the Resource interface you can access the resource as InputStream , URL , URI or File . 通过Resource接口,您可以将资源作为InputStreamURLURIFile访问 Changing the resource type to eg a file system resource is a simple matter of changing the instance. 将资源类型更改为例如文件系统资源是更改实例的简单问题。


#6楼

You say "I am trying to read a text file which is set in CLASSPATH system variable." 您说“我正在尝试读取在CLASSPATH系统变量中设置的文本文件。” My guess this is on Windows and you are using this ugly dialog to edit the "System Variables". 我猜这是在Windows上你正在使用这个丑陋的对话框来编辑“系统变量”。

Now you run your Java program in the console. 现在,您在控制台中运行Java程序。 And that doesn't work: The console gets a copy of the values of the system variables once when it is started . 这不工作:控制台获取系统变量,当它再次 起动的值的副本。 This means any change in the dialog afterwards doesn't have any effect. 这意味着之后对话框中的任何更改都不会产生任何影响。

There are these solutions: 有这些解决方案:

  1. Start a new console after every change 每次更改后都启动一个新控制台

  2. Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog. 在控制台中使用set CLASSPATH=...在控制台中设置变量的副本,当代码工作时,将最后一个值粘贴到变量对话框中。

  3. Put the call to Java into .BAT file and double click it. 将对Java的调用放入.BAT文件并双击它。 This will create a new console every time (thus copying the current value of the system variable). 这将每次创建一个新控制台(从而复制系统变量的当前值)。

BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. 请注意:如果您还有一个用户变量CLASSPATH那么它将影响您的系统变量。 That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH= ) rather than relying on a global system or user variable. 这就是为什么通常最好将对Java程序的调用放入.BAT文件并在那里设置类路径(使用set CLASSPATH= )而不是依赖于全局系统或用户变量。

This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths. 这也确保您可以在计算机上运行多个Java程序,因为它们必然具有不同的类路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值