1

File structure:

\a    
    programme.class
    programme.java
    \b
        text.txt

Having my current directory under \a (which means that the default classpath is set to \a as well) and having this for my code (for testing purpose):

System.out.println(programme.class.getClassLoader().getResource("b/text.txt"));

Running my programme from the folder \a doesn't require me to specify classpath for b. Hence, I can run my programme simply like this: java programme

Now, I thought that adding a directory to the classpath (in our case the default classpath is user.dir aka \a) doesn't resolve the subdirectories (doesn't add them recursively to classpath).

How does the classloader find the file b\text.txt in classpath?

  • I might be answering my own question here, correct me if I'm wrong. Since we are running our programme from folder \a , it adds all of its content to the classpath. That means that folder \b will appear on classpath. And therefore it will be able to locate text.txt ? – Jaroslav Gorshkov Jul 03 '18 at 11:16
  • See: https://stackoverflow.com/questions/16570523/getresourceasstream-returns-null – lexicore Jul 03 '18 at 11:16
  • 1
    The English word is “program”, not “programme”. Further, you should use `programme.class.getResource("b/text.txt")`, to resolve a resource relative to the location of the `programme` class. Otherwise, it may fail in Java 9 or newer, once you use modules, as going up to the class loader will destroy the information about the actual module. Besides that, it seems you are not aware of packages or how they are mapped when using a file system as class path entry. The class path contains root directories or archives, both containing classes which are usually in sub directories matching the package. – Holger Jul 04 '18 at 06:15

0 Answers0