Search code examples
javaurluri

How to get the path of a URL?


I have a URL. How do I retrieve its path part?

For example: Given "http://www.costo.com/test1/test2", how do I get "test1/test2"?


Solution

  • You want something like this:

    String path = new URL("http://www.costo.com/test1/test2").getPath();
    

    Actually that'll give you /test1/test2. You'll just have to remove the first / to get what you want:

    path = path.replaceFirst("/", "");
    

    Now you'll have test1/test2 in path.