我的项目结构如下:

/src/main/java/
/src/main/resources/
/src/test/java/
/src/test/resources/

我在/src/test/resources/test.csv中有一个文件,我想从/src/test/java/MyTest.java中的单元测试中加载该文件

我有个不能用的代码。它会提示“没有这样的文件或目录”。

BufferedReader br = new BufferedReader (new FileReader(test.csv))

我也试过这个

InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))

这也行不通。它返回null。我正在使用Maven构建我的项目。


当前回答

下面的类可用于从类路径加载资源,并在给定的filePath出现问题时接收适当的错误消息。

import java.io.InputStream;
import java.nio.file.NoSuchFileException;

public class ResourceLoader
{
    private String filePath;

    public ResourceLoader(String filePath)
    {
        this.filePath = filePath;

        if(filePath.startsWith("/"))
        {
            throw new IllegalArgumentException("Relative paths may not have a leading slash!");
        }
    }

    public InputStream getResource() throws NoSuchFileException
    {
        ClassLoader classLoader = this.getClass().getClassLoader();

        InputStream inputStream = classLoader.getResourceAsStream(filePath);

        if(inputStream == null)
        {
            throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
        }

        return inputStream;
    }
}

其他回答

getResource()只能在src/main/resources中使用资源文件。要获取src/main/resources路径之外的文件,比如src/test/java,你需要明确地创建它。

下面的例子可能会帮助你

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws URISyntaxException, IOException {
        URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
        BufferedReader br = new BufferedReader(new FileReader(location.getPath().toString().replace("/target/classes/", "/src/test/java/youfilename.txt")));
    }
}
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("test.csv");

如果使用上下文ClassLoader来查找资源,那么肯定会降低应用程序的性能。

当不运行Maven-build jar时(例如从IDE运行时),代码还能工作吗?如果是,请确保该文件确实包含在jar中。资源文件夹应该包含在pom文件中,在<build><resources>中。

this.getClass().getClassLoader().getResource("filename").getPath()

在Spring项目中尝试以下代码

ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();

或者在非弹簧项目上

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("fileName").getFile());
 InputStream inputStream = new FileInputStream(file);