Reading from src/main/resources gives NullPointerException

前端 未结 2 1718
执笔经年
执笔经年 2020-12-08 07:03

In my Maven project, I have a xls file in src/main/resources. When I read it like this:

 InputStream in = new
 FileInputStream(\"src/main/resources/WBU_templ         


        
相关标签:
2条回答
  • 2020-12-08 07:42

    FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process.

    getResourceAsStream() will load a file path relative from your application's classpath.

    When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.

    When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

    The file should be located in src/main/resources when loading using Class loader

    In short, you have to use .getClass().getClassLoader().getResource(fileName) to load the file in your case.

    0 讨论(0)
  • 2020-12-08 07:42

    I usually load files from WEB-INF like this

    session.getServletContext().getResourceAsStream("/WEB-INF/WBU_template.xls")
    
    0 讨论(0)
提交回复
热议问题