user1757703
user1757703

Reputation: 3015

Need the highest dir of the URL

new URL("http://example.com/public/files/random.php")

I want to fetch the highest directory of the URL when the URL ends with a file extension. For ex: that URL ends with .php so I want to fetch http://example.com/public/files/ from that. Is there a specific way to do this?

Upvotes: 0

Views: 41

Answers (2)

Reimeus
Reimeus

Reputation: 159794

Assuming you're looking for the address String minus the PHP page, you could use URI#resolve instead

URI uri = URI.create("http://example.com/public/files/random.php");
String noPage = uri.resolve("").toString();

Upvotes: 1

D180
D180

Reputation: 742

Yes, there is a way:

URL url = new URL("http://example.com/public/files/random.php");
String urlString = url.toString();
String fetched = urlString.substring(0, urlString.lastIndexOf('/'));

this finds the last slash and cuts the String there. If the URL doesn't end with an file extension, like "http://example.com/public/", then the last occurence of '/' is exactly the last character in the String, so nothing changes.

Upvotes: 3

Related Questions