Correct way of reading a file in src/main/resource

2020-05-06 14:08发布

问题:

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

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

Now I want to read sample.xml from MainFile.java as a string.

I tried using this method but got NoSuchFileException

byte[] encoded = Files.readAllBytes(Paths.get("src/main/resources/sample.xml"));
return new String(encoded, StandardCharsets.UTF_8);

Please suggest a solution to this issue.

回答1:

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.



回答2:

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