How to get list of files from jar?

Hello! How can I get list of icons in jar?
I tried using many classes, such as File, Files and others, but to no avail. At localhost all its ok

Hi,

Try to use this Spring class: PathMatchingResourcePatternResolver (Spring Framework 6.0.4 API)

Hello! Sorry, how I can use this class?

At localhost I have code:

public static List getListIconNames(String path) throws NullPointerException {
File dir = new File(path);
File[] list = dir.listFiles();
List filesList = Arrays.stream(list).map(File::getName).collect(Collectors.toList());
return filesList;
}

How can I get this list from uberjar?

Hi,

The thing is that you can’t handle files in Jar as File objects, instead either Resource or InputStream must be used. In case of a single file (resource), the Resources bean can be used, e.g.:

@Autowired
private Resources resources;

...

Resource resource = resources.getResource(path);

if (resource.exists()) {
    InputStream inputStream = resource.getInputStream();
    // ...
} else {
    // ...
}

In case of a directory PathMatchingResourcePatternResolver can be used, e.g.:

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] pathResources = resolver.getResources("com/company/demo/web/assets/icons/*");
// ...

I’ve prepared a demo project: classpath-files-demo.zip (87.2 KB)

Regards,
Gleb

Hi! Thank you very much. The problem was in the path. The icons were in the VAADIN folder, so the resource did not work

In order to obtain resources from VAADIN directory, the vaadin:// prefix must be used.

Hello, Gleb! Sorry, what path will be for VAADIN??

Something like that?

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] pathResources = resolver.getResources(“vaadin:///VAADIN/icons/*”);
List list = Arrays.stream(pathResources).map(Resource::getFilename).collect(Collectors.toList());

Sorry that I confused you with the vaadin:// prefix. It’s used for dependencies, so not applicable in your case.

First of all, let’s me explain what VAADIN directory is. VAADIN directory contains resources that is stored in the directory of deployed application, e.g.: ${catalina.base}/webapps/app/VAADIN/images/image.png.

What it means:

  1. It isn’t located in the resource folder.
  2. You have access to the files located in the VAADIN directory via URL, e.g.: http://localhost:8080/app/VAADIN/assets/images/image.png

Still you can iterate over files in the VAADIN directory using PathMatchingResourcePatternResolver.

In order to find correct path, I unzipped generated .jar file:

LIB-INF/app/WEB-INF/classes is a starting point for a relative path. Assuming I have assets/icons in the VAADIN directory, the correct path for PathMatchingResourcePatternResolver is ../../VAADIN/assets/icons

Testing this path, I got the following result:

Regards,
Gleb

Gleb, thanks! Everything works fine.