0

I was trying to read sub-directories(names of directories) of a directory in my class path resources using Spring Boot with snippet given below.

 public List<File> getSubdirectories() { File file = ResourceUtils.getFile("classpath:/database/scripts"); return Arrays.stream(file.listFiles()).filter(File::isDirectory).map(File::getFileName) .collect(Collectors.toList()); } 

Now this would work well when we run this code from IDE. But when we build this app as a jar and runs it from there it throws a FileNotFoundException.

I tried to load the directory as class path resource as well. But didn't find any luck.

I'm currently using Java 8. So most of the Java 7 solutions won't work I guess. Is there any other way I can resolve this issue?

0

1 Answer 1

1

As per Spring documentation ResourceUtils are to be used internally within the framework

Try using Resource instead:

@Value("classpath:database/scripts") Resource directories; 

Alternatively, you can use resource loader:

@Autowired ResourceLoader resourceLoader; ... public Resource loadDirectories() { return resourceLoader.getResource( "classpath:database/scripts"); } 
Sign up to request clarification or add additional context in comments.

6 Comments

This won't work well as I need child directory names of the parent directory.
Why not? Resource has getFile() method. You can check later if that file is directory and list everything like this List<String> result = new ArrayList<>(); search(".*\\.java", directories.getFile(), result);
I just realized you wrote the parent directory. Why not then just get the resource 'database'?
We can do this while we use an IDE. But from a JAR file this will fail. It will throw a file not found exception.
Have you checked if your directories actually exist inside your jar?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.