Correct way of reading a file in src/main/resources as string in a web application?

前端 未结 2 2057
暖寄归人
暖寄归人 2021-01-28 22:23

I have a web application which has following structure (partial).

Project Name
   src/main/java
       com.package
           MainFile.java
   src/main/resources         


        
相关标签:
2条回答
  • 2021-01-28 22:56

    Try this:

     ClassLoader loader = SomeClass.class.getClassLoader();
     InputStream is = loader.getResourceAsStream("sample.xml"));
    
     byte[] b = null;
     int numBytes = is.read(b);
    

    resources should be in the classpath and ClassLoader should find it for you.

    0 讨论(0)
  • 2021-01-28 23:06

    This file is in the web app classpath, so you can get it like:

    Path path = Paths.get(getClass().getResource("/sample.xml").toURI());
    return new String(Files.readAllBytes(path));
    
    0 讨论(0)
提交回复
热议问题