Preferred way of loading resources in Java

前端 未结 5 1597
走了就别回头了
走了就别回头了 2020-11-22 15:25

I would like to know the best way of loading a resource in Java:

  • this.getClass().getResource() (or getResourceAsStream()),
  • Thread.c
5条回答
  •  囚心锁ツ
    2020-11-22 15:46

    Work out the solution according to what you want...

    There are two things that getResource/getResourceAsStream() will get from the class it is called on...

    1. The class loader
    2. The starting location

    So if you do

    this.getClass().getResource("foo.txt");
    

    it will attempt to load foo.txt from the same package as the "this" class and with the class loader of the "this" class. If you put a "/" in front then you are absolutely referencing the resource.

    this.getClass().getResource("/x/y/z/foo.txt")
    

    will load the resource from the class loader of "this" and from the x.y.z package (it will need to be in the same directory as classes in that package).

    Thread.currentThread().getContextClassLoader().getResource(name)
    

    will load with the context class loader but will not resolve the name according to any package (it must be absolutely referenced)

    System.class.getResource(name)
    

    Will load the resource with the system class loader (it would have to be absolutely referenced as well, as you won't be able to put anything into the java.lang package (the package of System).

    Just take a look at the source. Also indicates that getResourceAsStream just calls "openStream" on the URL returned from getResource and returns that.

提交回复
热议问题