shekhart6405668
shekhart6405668
07-08-2019
Hi Guys,
I am using the AEM 6.2. and new to AEM. Can some one suggest me how to get the real path of the resource directory? i.e "src/main/resources".
Vish_dhaliwal
Employee
Vish_dhaliwal
Employee
07-08-2019
Hello,
Not related to your question. Just want to let you know that you should start upgrading to AEM 6.5 since the core support of 6.2 has ended.
All Apps Help | Products and technical support periods
Regards,
Vishu
rampai
rampai
08-08-2019
Hi shekhart64009905,
Do you want to read a file included in resources section?
mohitaem
mohitaem
08-08-2019
Shekhar is trying to access "src/main/resources" folder from the java code. He want to create, write, read and delete the file in the resources folder. Since we install the java project as bundle its not possible to hardcode the path so he is finding it difficult to read the path of "src/main/resources".
rampai
rampai
09-08-2019
If you want to manipulate the files using Java then you can use relative paths instead and take advantage of ClassLoader.
e.g. to read a file test.json inside test-folder under src/main/resources and get its contents in Java code:
InputStream is = getStreamFromResources("test-folder/test.json");
printFileContents(is);
If not inside a folder:
InputStream is = getStreamFromResources("test.json");
printFileContents(is);
Methods:
private static void printFileContents(InputStream inputStream) throws IOException {
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader
(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
jsonString = new String(textBuilder);
LOGGER.info(textBuilder.toString());
}
// get file contents as stream from classpath, resources folder
private InputStream getStreamFromResources(String fileName) {ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(fileName);
if (is == null) {
throw new IllegalArgumentException("file is not found!");
} else {
return is;
}
}
This is how my folder structure looks like:
Sample Output in HTL:
Regards,
Ram
shekhart6405668
shekhart6405668
09-08-2019
Hi Ram,
Thanks for response on this. Now file reading and writing inside test-folder make sense. But how can we listed all file inside the test-folder.
Jörg_Hoh
Employee
Jörg_Hoh
Employee
09-08-2019
If you want to access the files in the JAR file during runtime, you can use the "regular" API you would always use in java, this is not specific to AEM. On the other hand, I doubt that the test classes are part of the resulting JAR file.