Read File from Resources Folder in Spring Boot

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:

Sample Image


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

Sample Image

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



Leave a reply



Submit