How can I read a file inside a project ( resources folder ) when I host it as an azure function?
I tried with:
public static File GetFileFromResources(String pathFromResources) {
File file;
ClassLoader classLoader = FilesHelper.class.getClassLoader();
URL url = classLoader.getResource(pathFromResources);
file = new File(url.getFile());
return file;
}
However I get an exception:
[09.08.2020 18:05:08] Caused by: java.io.FileNotFoundException: C:\Users\Maciej-pc\Desktop\AzureFunctionsss\hl7edytorFunctions\target\azure-functions\hl7edytorFunctions-1596901248640\file:\C:\Users\Maciej-pc\Desktop\AzureFunctionsss\hl7edytorFunctions\target\azure-functions\hl7edytorFunctions-1596901248640\hl7edytorFunctions-1.0-SNAPSHOT.jar!\somethinng.xsl (Nazwa pliku, nazwa katalogu lub skladnia
etykiety woluminu jest niepoprawna)
[09.08.2020 18:05:08] at java.base/java.io.FileInputStream.open0(Native Method)
[09.08.2020 18:05:08] at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
[09.08.2020 18:05:08] at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
[09.08.2020 18:05:08] at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
The filename or folder name is incorrect.
I testing it on the local machine. I would like to get it works on localhost and Azure.
Ok here is a working method:
public static String GetFileInStringFromResources(String pathToResources) throws IOException {
// this is the path within the jar file
InputStream input = FilesHelper.class.getResourceAsStream("/resources/" + pathToResources);
// here is inside IDE
if (input == null) {
input = FilesHelper.class.getClassLoader().getResourceAsStream(pathToResources);
}
//here you can return (InputStream) input or you can return as string
//return input;
// convert InputStream to String
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString("UTF-8");
}