Java 中的资源、 URI、 URL、路径和文件有什么区别?

我现在正在查看一段 Java 代码,它采用一个 String 路径,并使用 URL resource = ClassLoader.getSystemClassLoader().getResource(pathAsString);获取其 URL,然后调用 String path = resource.getPath(),最后执行 new File(path);

还有打到 URL url = resource.toURI();String file = resource.getFile()的电话。

我现在完全糊涂了——我猜主要是因为术语的问题。谁能告诉我这些不同之处,或者提供一些防哑弹材料的链接?特别是 URI 到 URL 和 资源到文件?对我来说,它们应该是一样的,分别..。

这里解释了 getFile()getPath()之间的区别: GetFile ()和 getpath ()之间的区别是什么?(有趣的是,它们似乎都返回字符串,这可能给我的思维状态增加了很多... ...)

现在,如果我有一个引用 jar 文件中的类或包的定位器,那么这两者(即路径和文件字符串)是否会有所不同?

毕竟,abc0会给你带来 jar:file:/C:/path/to/my.jar!/com/example/(注意叹号)。

URI网址用爪哇语之间的区别是前者没有编码空格吗?参考 Java 中冲突的文件、 URI 和 URL(这个答案很好地解释了两个术语 一般的,概念性的之间的差异: URI 标识和 URL 定位;)

最后——也是最重要的—— 为什么我需要 ABC0对象; 为什么一个资源(URL)不够?(有 Resource 对象吗?)

对不起,如果这个问题有点杂乱无章,它只是反映了我的困惑... :)

53602 次浏览

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).

As I understand them, you could categorize them as following:

Web-Based: URIs and URLs.

  • URLs: An URL is a definite location on the internt (just a normal webaddress like - stackoverflow.com)
  • URIs: Ever URL is an URI. But URIs can also contain things like "mailto:", so they are also, well some what of a "script" I'd say.

And local: Resource, Path and Files

  • Resource: Resources are files inside your jar. They are used to load files out of jars / containers.
  • Path: A path is basically a string. But it comes with some handy functions to concatenate multiple strings, or add files to a string. It makes sure the path you are building is valid.
  • File: This is a reference to a directory or file. It's used to modify files, open them etc.

It would be easier if they would be merged into one class - they are really confusing :D

I hope this helps you :)

(I just took a look at the documentation - look at docs.oracle.com)

A File is an abstract representation of an entity in the local filesystem.

A path is generally a string indicating the location of a file within a file system. It usually doesn't include the filename. So c:\documents\mystuff\stuff.txt would have a path with the value of of "C:\documents\mystuff" Obviously the format of absolute filenames and paths would vary enormously from filesystem to filesystem.

URL is a susbset of URI with URL usually representing resources accessible over http. I don't think there is any sort of ironclad rule about when something has to be a URI vs a URL. URIs are strings in the form of "protocol://resource-identifier" such as bitcoin://params, http://something.com?param=value. Classes like URL generally wrap the string and provide utility methods that String would have no reason to supply.

No such thing as Resource, at least not in the sense you're talking about. Just because a method is named getResource doesn't mean it returns an object of type Resource.

Ultimately the best way to figure out what a Class's methods do is to create an instance of it in your code, call the methods and then either step through in debug mode or send the results to System.out.

Pavel Horal's answer is nice.

As he says, the word "file" has totally different (practically unrelated) meanings in URL#getFile vs java.io.File - may be that's part of the confusion.

Just to add:

  • A resource in Java is an abstract concept, a source of data that can be read. The location (or address) of a resource is represented in Java by a URL object.

  • A resource can correspond to a regular file in the local filesystem (specifically, when its URL begins with file://). But a resource is more general (it can be also some file stored in a jar, or some data to be read from the network, or from memory, or...). And it's also more limited, because a File (besides being other things than a regular file: a directory, a link) can also be created and writen to.

  • Remember in Java a File object does not really represents "a file" but the location (the full name, with path) of a file. So, a File object allows you to locate (and open) a file, as a URLallows you to access (and open) a resource. (There is no Resource class in Java to represent a resource, but neither there is one to represent a file! once more : File is not a file, it's the path of a file).

I'm totally confused right now - mostly because of the terminology, I guess. Can someone please walk me through the differences, or provide a few links to Dummy-proof material? Especially URI to URL and Resource to File? To me, it feels like they should be the same thing, respectively...

The terminology is confusing and sometimes befuddling, and mostly born from the evolution both of Java as an API and as a platform over time. To understand how these terms came to mean what they do, it is important to recognise two things that influence Java's design:

  • Backwards compatibility. Old applications should run on newer installations, ideally without modification. This means that an old API (with its names and terminology) needs to be maintained through all newer versions.
  • Cross-platform. The API should provide a usable abstraction of its underlying platform, whether that be an operating system or a browser.

I'll walk through the concepts and how they came to be. I'll answer your other, specific questions after that, because I may have to refer to something in the first part.

What is a "Resource"?

An abstract, generic piece of data that can be located and read. Loosely said, Java uses this to refer to a "file" that may not be a file but does represent a named piece of data. It does not have a direct class or interface representation in Java, but because of its properties (locatable, readable) it is often represented by an URL.

Because one of Java's early design goals was to be run inside of a browser, as a sandboxed application (applets!) with very limited rights/privileges/security clearance, Java makes a clear (theoretical) difference between a file (something on the local file system) and a resource (something it needs to read). This is why reading something relative to the application (icons, class files, and so on) is done through ClassLoader.getResource and not through the File class.

Unfortunately, because "resource" is also a useful generic term outside of this interpretation, it is also used to name very specific things (e.g. class ResourceBundle, UIResource, Resource) that are not, in this sense, a resource.

The main classes representing (a path to) a resource are java.nio.file.Path, java.io.File, java.net.URI, and java.net.URL.

File (java.io, 1.0)

An abstract representation of file and directory pathnames.

The File class represents a resource that is reachable through the platform's native file system. It contains only the name of the file, so it is really more a path (see later) that the host platform interprets according to its own settings, rules, and syntax.

Note that File doesn't need to point to something local, just something that the host platform understands in the context of file access, e.g. a UNC path in Windows. If you mount a ZIP file as a file system in your OS, then File will read its contained entries just fine.

URL (java.net, 1.0)

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.

In tandem with the concept of a resource, the URL represents that resource the same way the File class represents a file in the host platform: as a structured string that points to a resource. URL additionally contains a scheme that hints at how to reach the resource (with "file:" being "ask the host platform"), and so allows pointing at resources through HTTP, FTP, inside a JAR, and whatnot.

Unfortunately, URLs come with their own syntax and terminology, including the use of "file" and "path". In case the URL is a file-URL, URL.getFile will return a string identical to the path string of the referenced file.

Class.getResource returns an URL: it is more flexible than returning File, and it has served the needs of the system as imagined in the early 1990's.

URI (java.net, 1.4)

Represents a Uniform Resource Identifier (URI) reference.

URI is a (slight) abstraction over URL. The difference between URI and URL is conceptual and mostly academic, but URI is better defined in a formal sense, and covers a wider range of use cases. Because URL and URI are/were not the same thing, a new class was introduced to represent them, with methods URI.toURL and URL.toURI to move between one and the other.

In Java, the main difference between URL and URI is that an URL carries the expectation of being resolvable, something the application might want an InputStream from; an URI is treated more like an abstract thingamajig that might point to something resolvable (and usually does), but what it means and how to reach it are more open to context and interpretation.

Path (java.nio.file, 1.7)

An object that may be used to locate a file in a file system. It will typically represent a system dependent file path.

The new file API, iconified in the Path interface, allows for much greater flexibility than the File class could offer. The Path interface is an abstraction of the File class, and is part of the New IO File API. Where File necessarily points to a "file" as understood by the host platform, Path is more generic: it represents a file (resource) in an arbitrary file system.

Path takes away the reliance on the host platform's concept of a file. It could be an entry in a ZIP file, a file reachable through FTP or SSH-FS, a multi-rooted representation of the application classpath, or really anything that can be meaningfully represented through the FileSystem interface and its driver, FileSystemProvider. It brings the power of "mounting" file systems into the context of a Java application.

The host platform is represented through the "default file system"; when you call File.toPath, you get a Path on the default file system.


Now, if I have a locator that references a class or package in a jar file, will those two (i.e. path an file strings) differ?

Unlikely. If the jar file is on the local file system, you should not have a query component, so URL.getPath and URL.getFile should return the same result. However, pick the one you need: file-URLs may not typically have query components, but I could sure add one anyway.

Lastly - and most importantly - why do I need File object; why isn't a Resource (URL) enough?

URL might not be enough because File gives you access to housekeeping data such as permissions (readable, writable, executable), file type (am I a directory?), and the ability to search and manipulate the local file system. If these are features you need, then File or Path provide them.

You don't need File if you have access to Path. Some older API may require File, though.

(And is there a Resource object?)

No, there isn't. There are many things named like it, but they are not a resource in the sense of ClassLoader.getResource.