How do I reference a resource in Java?

前端 未结 2 1491
名媛妹妹
名媛妹妹 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");
    
    0 讨论(0)
  • 2020-12-14 22:33

    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.

    0 讨论(0)
提交回复
热议问题