I want to create a String from the content of the file. According this answer I do it in this way:
private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(stringTemplatePath));
return new String(encoded, "UTF-8");
}
(As I understand this is a path of new NIO2 API, that is a part of Java 7.)
stringTemplatePath parameter is a name of the file ("template.html"). I check location of this file. It is in the classpath: ../classes/template.html
After calling this function I get an exception:
java.nio.file.NoSuchFileException: template.html
Maybe I send filename parameter to in a wrong way? I tried to send this modification: "file:///template.html" and "classpath:template.html", but it didn't help.
Also I tried this code:
private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
File file = new File(stringTemplatePath);
String absolutePath = file.getAbsolutePath();
byte[] encoded = Files.readAllBytes(Paths.get(absolutePath));
return new String(encoded, "UTF-8");
}
I called this function I get following exception:
java.nio.file.NoSuchFileException: /opt/repo/versions/8.0.9/temp/template.html
So, file in classpath because new File(stringTemplatePath) can create a File. But this file has very strange path (/opt/repo/versions/8.0.9/temp/template.html). I use Jelastic as hosting (enviroment: Java 8, Tomcat 8), if it is metter.
UPDATE: FINAL WORKING SOLUTION:
private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream(stringTemplatePath);
return IOUtils.toString(inputStream, "UTF-8");
}
IOUtils is util class from Apache IO Commons.
Impotant note:
If I just invoke .getResourceAsStream(...) from class, resource file will be not find and method will return null:
MyClass.class.getResourceAsStream(stringTemplatePath);
So, I call .getClassLoader() before calling .getResourceAsStream(...) and it works perfectly:
MyClass.class.getClassLoader().getResourceAsStream(stringTemplatePath);