How i can read any file from resources folder in java spring-boot AZURE function?
Try with this code:
InputStream resourceInputStream = new FileInputStream(HelloFunction.class.getClassLoader().getResource("").getPath()+"../../src/main/java/com/example/resources/hello.json");
My source code structure is like below:
UPDATE:
String pathToResources = "hello.json";
// this is the path within the jar file
InputStream input = HelloHandler.class.getResourceAsStream("/resources/" + pathToResources);
// here is inside IDE
if (input == null) {
input = HelloHandler.class.getClassLoader().getResourceAsStream(pathToResources);
}
// 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);
}
System.out.println(result.toString("UTF-8"));
SpringBoot - accessing a file inside resources folder
It's depends on your requirements..
Case 1:
Considering you need to access text file from resource. You can simply use apache IOUtils
and java ClassLoader
.
Snippet (note: IOUtils package --> org.apache.commons.io.IOUtils)
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream("fileName"));
} catch (IOException e) {
e.printStackTrace();
}
Classic way:
StringBuilder result = new StringBuilder("");
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
Case 2:
Considering you need to access properties from resources such as xml, properties files.
Its too simple, Simply use spring annotation @ImportResource({ "classpath:application-properties.xml", "classpath:context.properties" })
Hope that will be helpful to you.
Related Topics
Java Wait for Thread to Finish
How to Enumerate All Classes in a Package and Add Them to a List
How to Remove Leading Zeros from Alphanumeric Text
Override Default Spring-Boot Application.Properties Settings in Junit Test
Jformattedtextfield:Input Time Duration Value
Drawing an Object Using Getgraphics() Without Extending Jframe
What Does an Assignment Expression Evaluate to in Java
Running Multiple Launch Configurations at Once
"Int Cannot Be Dereferenced" in Java
Java Date - Insert into Database
The Simplest Way to Comma-Delimit a List
How to Print Line Numbers to the Log in Java
Maven Compilation Error: (Use -Source 7 or Higher to Enable Diamond Operator)
Java Division by Zero Doesnt Throw an Arithmeticexception - Why
How to Format Localdate Object to Mm/Dd/Yyyy and Have Format Persist