我的项目结构如下:

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


当前回答

现在我正在说明从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());

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

我得到了它的工作在运行的罐子和IDE通过编写

InputStream schemaStream = 
      ProductUtil.class.getClassLoader().getResourceAsStream(jsonSchemaPath);
byte[] buffer = new byte[schemaStream.available()];
schemaStream.read(buffer);

File tempFile = File.createTempFile("com/package/schema/testSchema", "json");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
out.write(buffer);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("test.csv");

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

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