How do I reference a resource in Java?

前端 未结 2 1497
名媛妹妹
名媛妹妹 2020-12-14 22:07

I need to read a file in my code. It physically resides here:

C:\\eclipseWorkspace\\ProjectA\\src\\com\\company\\somePackage\\MyFile.txt

I

2条回答
  •  执笔经年
    2020-12-14 22:30

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

提交回复
热议问题