我试图读取在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到我的输入流。


当前回答

如果你在jar文件中编译项目: 你可以把你的文件放在resources/files/your_file中。文本或pdf;

并使用这段代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;

public class readFileService(){
    private static final Logger LOGGER = LoggerFactory.getLogger(readFileService.class);


    public byte[] getFile(){
        String filePath="/files/your_file";
        InputStream inputStreamFile;
        byte[] bytes;
        try{
            inputStreamFile = this.getClass().getResourceAsStream(filePath);
            bytes = new byte[inputStreamFile.available()];
            inputStreamFile.read(bytes);    
        } catch(NullPointerException | IOException e) {
            LOGGER.error("Erreur read file "+filePath+" error message :" +e.getMessage());
            return null;
        }
        return bytes;
    } 
}

其他回答

通过类路径上的目录,从同一个类加载器加载的类中,你应该能够使用以下任何一种:

// 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
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile

{
    /**
     * * feel free to make any modification I have have been here so I feel you
     * * * @param args * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {
        // thread pool of 10
        File dir = new File(".");
        // read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }

}

我使用webshpere应用服务器和我的Web模块是建立在Spring MVC。测试。属性位于资源文件夹中,我尝试使用以下方法加载此文件:

.getResourceAsStream .getClassLoader this.getClass()()(“Test.properties”); this.getClass () .getResourceAsStream (" / Test.properties ");

上面的代码都没有加载文件。

但是在下面代码的帮助下,属性文件被成功加载:

.getResourceAsStream .getContextClassLoader Thread.currentThread()()(“Test.properties”);

感谢用户“user1695166”。

你必须把你的“系统变量”放在Java类路径上。

不要使用getClassLoader()方法,并在文件名前使用“/”。“/”非常重要

this.getClass().getResourceAsStream("/SomeTextFile.txt");