0

When I want to load a file or asset(say an image) from file system into my program, I could either read the file directly from file system using something like

Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);

vs loading the file as a resource

getClass().getClassLoader().getResourceAsStream(fileName);

In Javadoc, Class#getResource() method, Javadoc specifies Resources in named modules are subject to the rules for encapsulation specified in the {@code Module} {@link Module#getResourceAsStream getResourceAsStream} method and so this method returns {@code null} when the resource is a non-"{@code .class}" resource in a package that is not open to the caller's module. but I somehow could not wrap my head around what would be the deciding factor for me to load a file as a resource or simply read it from file system.

Shashi
  • 746
  • 10
  • 39
  • 1
    File: actual file on the file system. Resource: you can put files inside of a Jar file and load them with `getResource`, they don't need to be separate (or downloaded separately). This is convenient when the end user is receiving a Jar file instead of using a full app installer on their system. – markspace Mar 03 '20 at 19:09
  • nah, it mentions "if your properties exist in some folder in the physical filesystem (e.g. user folder, ...) use FileInputStream and if the file is embedded in your classpath (e.g. as a resource inside the JAR) use getResourceAsStream". But doesn't explain on the why part. as in why would I put a file as a resource instead of as a file. What explains the fundamental difference between the two approaches is what I'm curious about. – Shashi Mar 03 '20 at 20:06

0 Answers0