Java reading and interpreting resource, absolute and relative paths

How to load java resources?

Java is read from the environment resources, in most cases, java jar retrieved directly in the Classpath. Because the code is running and load-independent resource location, resource loading java is referred to as location independent, java only need to find the right environment resources.

Absolute and relative paths

Resources are referenced using the resource name: getResourceAsStream("/path/resource.xml");

Which "/path/resource.xml"is the name of the resource;

Resource names can be:

  • Absolute path, for example "/path/resource.xml"; begins with '/' is the absolute path

  • Relative path, for example, "path / resource.xml";

Refers to a relative path with respect to the position of the method is called, the path will be spliced, the path will be the absolute / removal directly

package my.location;

class ResourceFinder {
...
public void findResources(){
  InputStream stream1 =
getClass().getResourceAsStream("/path/resource.xml");
  InputStream stream2 =
getClass().getResourceAsStream("path/resource.xml");
}
...
}
  • stream1 path for access to resourcespath/resource.xml

  • stream2 access to resources pathmy/location/path/resource.xml

ClassLoader and Class of different treatments on the file name

ClassLoader.getResource()And Class.getResource()work in different ways

ClassLoader use the given string directly without using a conversion path absolute / relative path name as a resource, and therefore can not begin with string /

package my.location;

class ResourceFinder {
...
public void findResources(){
  InputStream stream1 =
getClass().getResourceAsStream("/path/resource.xml");
  InputStream stream2 =
getClass().getResourceAsStream("path/resource.xml");
  InputStream stream3 =
getClass().getClassLoader().getResourceAsStream("path/resource.xml");
  InputStream stream4 =
getClass().getClassLoader().getResourceAsStream("/path/resource.xml");

}
...
}

stream3 file path is path/resource.xml, and the path is illegal stream4

 

 

references:

http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading

    

Guess you like

Origin www.cnblogs.com/zad27/p/11204702.html