url and uri difference in java

I meet a tricky thing when tried to get resource path from ClassLoader.  The code is as below:

val resource = "some-resource" // the path contains %
val url = this.getClass.getClassLoader.getResource(resource)

val urlPath = url.getPath
val uriPath = url.toURI.getPath
println(urlPath == uriPath) // return false

The key point is that % will be encoded to %25 in URL but keep originally in URI. And if you want to use the real path of the resource, please use URI always, like

new File(url.toURI())

Otherwise you will never locate the file.

More about url encoding:

Url encoding is also known as percentage encoding since it uses percent sign as an escape character. Disallowed characters will be converted to bytes first and each byte will be converted to 2 hex number preceded with %.