我的项目结构如下:

/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构建我的项目。


当前回答

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

其他回答

我也遇到过同样的问题。

类装入器没有找到该文件,这意味着它没有打包到工件(jar)中。您需要构建项目。例如,使用maven:

mvn clean package

因此,您添加到资源文件夹中的文件将进入maven构建,并对应用程序可用。

我想保留我的答案:它没有解释如何读取文件(其他答案解释了这一点),它回答了为什么InputStream或资源为空。这里也有类似的答案。

如果你是加载文件在静态方法,那么 ClassLoader ClassLoader = getClass().getClassLoader(); 这可能会给您一个错误。

你可以试试这个 例如,你想从resources加载的文件是resources >> Images >> Test.gif

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource resource = new ClassPathResource("Images/Test.gif");

    File file = resource.getFile();

对于1.7之后的java

 List<String> lines = Files.readAllLines(Paths.get(getClass().getResource("test.csv").toURI()));

或者,如果你在Spring回声系统中,你可以使用Spring utils

final val file = ResourceUtils.getFile("classpath:json/abcd.json");

想了解更多幕后消息,请查看下面的博客

https://todzhang.com/blogs/tech/en/save_resources_to_files

现在我正在说明从maven创建的资源目录中读取字体的源代码,

可控硅/主/资源/ calibril.ttf

Font getCalibriLightFont(int fontSize){
    Font font = null;
    try{
        URL fontURL = OneMethod.class.getResource("/calibril.ttf");
        InputStream fontStream = fontURL.openStream();
        font = new Font(Font.createFont(Font.TRUETYPE_FONT, fontStream).getFamily(), Font.PLAIN, fontSize);
        fontStream.close();
    }catch(IOException | FontFormatException ief){
        font = new Font("Arial", Font.PLAIN, fontSize);
        ief.printStackTrace();
    }   
    return font;
}

它为我工作,希望整个源代码也将帮助你,享受!

从src/resources文件夹读取文件,然后尝试这样做:

DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));

public static File getFileHandle(String fileName){
       return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}

对于非静态引用:

return new File(getClass().getClassLoader().getResource(fileName).getFile());