Piotr S
Piotr S

Reputation: 3

Java ClassLoader.getResourceAsStream(path) return null when resource is inside nested jar

My springboot project (project A) has dependency to library (library B) which is jar file (it's also my project, but source code is not present during compilation project A). Inside jar I have directory dir1 with one file file2.

Project structure:

- project A
-- src/main/java/com/test/ResourcesUtils.java
-- src/main/resources/dir1/file1

- library B
-- src/main/resources/dir1/file2

When I try to get resource from project A everything works fine for example:

InputStream is1 = ResourcesUtils.class.getClassLoader().getResourceAsStream("dir1\\file1);
InputStream is2 = ResourcesUtils.class.getClassLoader().getResourceAsStream("dir1/file1);

Both (is1, is2) are not null.

When I try to get resource from library B using the same method it does not work

InputStream is1 = ResourcesUtils.class.getClassLoader().getResourceAsStream("dir1\\file2);
InputStream is2 = ResourcesUtils.class.getClassLoader().getResourceAsStream("dir1/file2);

Variable is1 is null, is2 is not null.

Am I doing something wrong? Why it works different for resource from main jar than from dependent jar?

I can't just switch to second version (with '/', because I'm not controlling string which is passed to getResourceAsStream)

public static boolean existsInResource(Path path) {

try (InputStream is = ResourcesUtils.class.getClassLoader().getResourceAsStream(path.toString())) {
      return is != null;
    } catch (final IOException e) {
      // handle exception
    }
  }

Upvotes: 0

Views: 1616

Answers (1)

Peter Verhas
Peter Verhas

Reputation: 293

When referring to file1, it is a physical file in your application, and I assume that you run your code on Windows. The file file1 is in the Windows file system.

When referring to file2, it is inside a JAR file. That is not a windows file system, it is a JAR file.

Unless you know that the file is a physical file, it is safer to use the forward slash. The \ is a residue from the old 32-bit windows before Windows NT. Windows NT inside (I am not sure if I remember it correctly) uses /, and the command processor only uses the \.

Upvotes: 1

Related Questions