简体   繁体   中英

URL parse without String split

Java has cool URL parser

import java.net.*;
import java.io.*;

public class ParseURL {
public static void main(String[] args) throws Exception {

    URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                       + "/index.html?name=networking#DOWNLOADING");

    System.out.println("path = " + aURL.getPath());
}
}

Here is the output displayed by the program:

path = /docs/books/tutorial/index.html

I would like to take only this part : docs/books/tutorial (or /docs/books/tutorial/ ) Guessing don`t use string split, I am looking for other better resolution for this task.

Thank you in advance

String path = "/docs/books/tutorial/index.html";
path = path.substring(1, path.lastIndexOf("/"));

gives docs/books/tutorial

You can do it with a File Object, rather than split your String:

Working example:

import java.io.File;
import java.net.URL;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("path = " + aURL.getPath());

        File file = new File(aURL.getPath());

        System.out.println("pathOnly = " + file.getParent());
    }
}

Output:

path = /docs/books/tutorial/index.html
pathOnly = /docs/books/tutorial

There are few ways. One of them is using URI#resolve(".") where . represents current directory . So your code can look like:

URI uri = new URI("http://example.com:80/docs/books/tutorial"
        + "/index.html?name=networking#DOWNLOADING");
System.out.println(uri.resolve(".").getPath());

Output: /docs/books/tutorial/


Other way could involve file system and classes which handle it like File or its improved version introduced in Java 7 Path (and its utility class Paths ).
These classes should allow you to parse path

/docs/books/tutorial/index.html

and get its parent location /docs/books/tutorial .

URL aURL = new URL("http://example.com:80/docs/books/tutorial"
        + "/index.html?name=networking#DOWNLOADING");

String path = aURL.getPath();
String parent = Paths.get(path).getParent().toString();

System.out.println(parent);// \docs\books\tutorial

(little warning: depending on your OS you may get path separated with \\ instead of / )

Take this as a example:

public static String getCustomPath() {
    String path = "/docs/books/tutorial/index.html";
    String customPath = path.substring(0, path.indexOf("index.html"));
    return customPath;
}

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