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");