I have a Spring Maven project I'm trying to load a random file from a folder in classpath
but I'm getting nullpointer in files
Folder I want -> src/main/resources/images/common/
Why classpath:
is not being interperted? How can I fix my code?
File[] files = new File("classpath:images/common/").listFiles();
private byte[] getRandomFile() throws IOException {
Random rand = new Random();
File file = files[rand.nextInt(files.length)]; //null pointer
return Files.readAllBytes(file.toPath());
}
I also tried
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource("images/common/");
String path = url.getPath();
File[] files = new File(path).listFiles();
private byte[] getRandomFile() throws IOException {
Random rand = new Random();
File file = files[rand.nextInt(files.length)];
return Files.readAllBytes(file.toPath());
}