0

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());
}
Tiago Silva
  • 229
  • 2
  • 9
  • The `File` object is for naming files on the *file system*. The classpath is not a file system. – Andreas Apr 15 '20 at 14:36
  • check my edit. This also gives me null pointer – Tiago Silva Apr 15 '20 at 14:38
  • Make a list of the items to choose from, count the list, generate a random number between 0 and count-1, pull that item from the list using the random index. Works for nested files, files in a directory, customer records, or anything. Good luck! – Edwin Buck Apr 15 '20 at 14:45
  • As per @EdwinBuck, and as you have shown you already know how to select a random element of list, you just need to correctly get the list of files (which is the problem in your code). This is covered in great length in the answers to question https://stackoverflow.com/questions/3923129 . – Guss Apr 15 '20 at 18:13

0 Answers0