newguy
newguy

Reputation: 3

Split arraylist for specific info from a URL?

I'm a bit confused with how to split my arraylist, loop thru the list, and pull out only specific info.

I have an arraylist of 20 URLs:
"http://xxxx.websitename.com:1234/aaa/bbb/ccc"
"http://yyyy.websitename.com:5678/aaa/bbb/ccc"
etc.....

And I want to be able to have the results pull only:
xxxx 1234
yyyy 5678

How do I get this started if I want the above as my result? I can find how to do it as a string, but no good example as an array list.

public class HealthCheck {

public static void main(String[] args) {

ArrayList arlURL = new ArrayList();
arlURL.add("http://xxxx.websitename.com:1234/aaa/bbb/ccc");
arlURL.add("http://yyyy.websitename.com:5678/aaa/bbb/ccc");

System.out.println(arlURL);

Upvotes: 0

Views: 118

Answers (1)

MrTux
MrTux

Reputation: 34032

There is no way to get only the (sub)domain and port by only using the ArrayList implementation. You can only get the entries as you put them into the ArrayList.

Use the build in URL class to parse the URLs of the ArrayList:

    URL aURL = new URL("http://xxxx.websitename.com:1234/aaa/bbb/ccc");

    System.out.println("protocol = " + aURL.getProtocol());
    System.out.println("authority = " + aURL.getAuthority());
    System.out.println("host = " + aURL.getHost());
    System.out.println("port = " + aURL.getPort());
    System.out.println("path = " + aURL.getPath());
    System.out.println("query = " + aURL.getQuery());
    System.out.println("filename = " + aURL.getFile());
    System.out.println("ref = " + aURL.getRef());

See http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

As you only want to have to subdomain you have to further split the aURL.getHost() string at the first dot (e.g., aURL.getHost().substring(0, aURL.getHost().indexOf(".")), be aware to first check that the string contains a dot before using this...).

Upvotes: 1

Related Questions