What's the difference between a Resource, URI, URL, Path and File in Java?

前端 未结 5 1729
無奈伤痛
無奈伤痛 2020-11-29 16:24

I\'m looking at a piece of Java code right now, and it takes a path as a String and gets its URL using URL resource = ClassLoader.getSystemClassLoader().getResource(pa

5条回答
  •  盖世英雄少女心
    2020-11-29 16:55

    UPDATE 2017-04-12 Check JvR's answer as it contains more exhaustive and exact explanation!


    Please note that I do not consider myself 100% competent to answer, but nevertheless here are some comments:

    • File represents a file or directory accessible via file system
    • resource is a generic term for a data object which can be loaded by the application
      • usually resources are files distributed with the application / library and loaded via class-loading mechanism (when they reside on class-path)
    • URL#getPath is getter on the path part of URL (protocol://host/path?query)
    • URL#getFile as per JavaDoc returns path+query

    In Java, URI is just a data structure for manipulating the generic identifier itself.

    URL on the other hand is really a resource locator and offers you features to actually read the resource via registered URLStreamHandlers.

    URLs can lead to file-system resources and you can construct URL for every file system resource by using file:// protocol (hence File <-> URL relation).

    Also be aware that that URL#getFile is unrelated to java.io.File.


    Why do I need File object; why isn't a Resource (URL) enough?

    It is enough. Only if you want to pass the resource to some component which can work only with files, you need to get File from it. However not all resource URLs can be converted to Files.

    And is there a Resource object?

    From the JRE point of view, it's just a term. Some frameworks provide you with such class (e.g. Spring's Resource).

提交回复
热议问题