I checked the place of concern of java.net.URL # getPath
The content of the article is verified with Java 8.
Overview
Make a note of how the'/' is handled in the character string obtained by getPath (), because I get excited every time I write the code.
Summary
- Only'/' is returned even if the path is completely omitted
- However, if both host and path do not exist, an empty string is returned.
- The trailing'/' is not omitted
- It shouldn't be pointed out because it shouldn't be omitted in the first place
Example
URL |
getPath() |
http://host |
/ |
http://host/ |
/ |
http://host/path |
/path |
http://host/path/ |
/path/ |
http://host?query |
/ |
http://host/?query |
/ |
http://host/path?query |
/path |
http://host/path/?query |
/path/ |
http:// |
(Empty string) |
http:/// |
/ |
http:///path |
/path |
Points to keep in mind
- It is guaranteed to start with'/', so the following description is fine
path.startsWith("/path");
- It is guaranteed to start with'/', so if you cut out an element with split ("/"), the first element will always be an empty string ... you need to skip it.
- ** However, note that split ("/") returns an array of size 0 for paths with only "/" **
String a[]=path.split("/");
if(a[1].equals("path")) {} //The path is"/"Exception occurs in case of
- The trailing'/' is not omitted, so be careful when writing the following:
path.endsWith("tail"); //"/path/tail/"If it is, it will be false
- getPath () probably won't return null
- It should not be null for instantiating by passing the URL string to the constructor