You need to treat them as a classpath resource, not as a local disk file system path. This isn't going to work when you package the files in a JAR and you also don't want to be dependent on the working directory. Files inside a JAR are part of the classpath already.
Assuming that you've a foo.txt
file in package com.example
, then you can get an InputStream
of it as follows
InputStream input = getClass().getResourceAsStream("/com/example/foo.txt");
// ...
Or when you're inside static
context
InputStream input = SomeClass.class.getResourceAsStream("/com/example/foo.txt");
// ...
Or when you want to scan the global classpath
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/com/example/foo.txt");
// ...
See also:
- How to read file from relative path in Java project? java.io.File cannot find the path specified
- getResourceAsStream() vs FileInputStream