有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring如何将java/resources文件获取到InputStream?

我在src/main/resources(/resources/files/templates)中有一个excel文件。我想把它读到InputStream。我没有找到正确的语法

String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";

    try {
        InputStream inputStream = new URL("file:///"  + fn).openStream();

上面的代码不起作用。我认为这条路错了。如何为存储在资源中的文件提供正确的路径


共 (2) 个答案

  1. # 1 楼答案

    这个适合我

    InputStream is = YourClass.class.getClassLoader().getResourceAsStream("relative path to your file starting from resources folder");
    
  2. # 2 楼答案

    如果使用任何方法(静态或非静态):

    String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";
    InputStream in = Clazz.class.getResourceAsStream(fn);
    

    其中Clazz是您所在的类的名称


    如果您使用的是非静态方法:

    String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";
    InputStream in = getClass().getResourceAsStream(fn);