简体   繁体   中英

Java URI local file system resolve issue

I have a two URI's and I want to concat the file from the second URI like the below: ...

  URI uri1 = new URI("file:/C:/Users/TestUser/Desktop/Example_File/");
  URI uri2 = new URI("/Example_File.xlsx");

after uri1.resolve(uri2) I want to get -> file:/C:/Users/TestUser/Desktop/Example_File/Example_File.xlsx

... The above resolve uri returns file:/Exampe_File.xlsx, which is not my expected result. How to do concat these two URI's?

To resolve, the second URI should not have the leading /

URI uri1 = new URI("C:/Users/TestUser/Desktop/Example_File/");
URI uri2 = new URI("Example_File.xlsx");
System.out.println(uri1.resolve(uri2)); 
// C:/Users/TestUser/Desktop/Example_File/Example_File.xlsx

From the documentation of URI#resolve(URI) :

[...]

Otherwise this method constructs a new hierarchical URI in a manner consistent with RFC 2396 , section 5.2; that is:

  1. A new URI is constructed with this URI's scheme and the given URI's query and fragment components.
  2. If the given URI has an authority component then the new URI's authority and path are taken from the given URI.
  3. Otherwise the new URI's authority component is copied from this URI, and its path is computed as follows:
    1. If the given URI's path is absolute then the new URI's path is taken from the given URI. [emphasis added]
    2. Otherwise the given URI's path is relative, and so the new URI's path is computed by resolving the path of the given URI against the path of this URI. This is done by concatenating all but the last segment of this URI's path, if any, with the given URI's path and then normalizing the result as if by invoking the normalize method.

And the class documentation of URI states:

The path component of a hierarchical URI is itself said to be absolute if it begins with a slash character ('/') [emphasis added] ; otherwise it is relative. The path of a hierarchical URI that is either absolute or specifies an authority is always absolute.

Since you have URI uri2 = new URI("/Example_File.xlsx") you are resolving a URI with an absolute path against another URI. This means, according to the documentation, that the resulting URI's path will be the path of uri2 . To fix this, make the path of uri2 a relative path. For example:

URI uri1 = new URI("file:/C:/Users/TestUser/Desktop/Example_File/");
URI uri2 = new URI("Example_File.xlsx"); // notice no leading slash

System.out.println(uri1.resolve(uri2));

Output:

file:/C:/Users/TestUser/Desktop/Example_File/Example_File.xlsx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM