I need to read a file in my code. It physically resides here:
C:\\eclipseWorkspace\\ProjectA\\src\\com\\company\\somePackage\\MyFile.txt
I
Use ClassLoader.getResourceAsStream or Class.getResourceAsStream. The main difference between the two is that the ClassLoader
version always uses an "absolute" path (within the jar file or whatever) whereas the Class
version is relative to the class itself, unless you prefix the path with /.
So if you have a class com.company.somePackage.SomeClass
and com.company.other.AnyClass
(within the same classloader as the resource) you could use:
SomeClass.class.getResourceAsStream("MyFile.txt")
or
AnyClass.class.getClassLoader()
.getResourceAsStream("com/company/somePackage/MyFile.txt");
or
AnyClass.class.getResourceAsStream("/com/company/somePackage/MyFile.txt");
If I have placed i file in a jar file, it only worked if and only if I used
...getResourceAsStream("com/company/somePackage/MyFile.txt")
If I used a File object it never worked. I got also the FileNotFound exception. Now, I stay with the InputStream object.