user1757703
user1757703

Reputation: 3015

Java: String manipulation. Fetch last subpath in a URL

Lets say I have a URL http://example.com/files/public_files/test.zip and I want to extract the last subpath so test.zip, How would I be able do this?

I am from Python so I am still new to Java and learning. In Python you could do something like this:

>>> x = "http://example.com/files/public_files/test.zip"
>>> x.split("/")[-1]
'test.zip'

Upvotes: 1

Views: 1148

Answers (4)

mistahenry
mistahenry

Reputation: 8724

Most similar to the python syntax is :

String url = "http://example.com/files/public_files/test.zip";
String [] tokens = url.split("/");
String file = tokens[tokens.length-1];

Java lacks the convenient [-n] nth to last selector that Python has. If you wanted to do it all in one line, you'd have to do something gross like this:

String file = url.split("/")[url.split("/").length-1];

I don't recommend the latter

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213193

Using String class method is a way to go. But given that you are having a URL, you can use java.net.URL.getFile():

String url = "http://example.com/files/public_files/test.zip";
String filePart = new URL(url).getFile();

The above code will get you complete path. To get the file name, you can make use of Apache Commons - FilenameUtils.getName():

String url = "http://example.com/files/public_files/test.zip";
String fileName = FilenameUtils.getName(url);

Well, if you don't want to refer to 3rd party library for this task, String class is still an option to go for. I've just given another way.

Upvotes: 1

Mac
Mac

Reputation: 1495

you can use the following:

String url = "http://example.com/files/public_files/test.zip";
String arr[] = url.split("/");
String name = arr[arr.length - 1];

Upvotes: 0

jlordo
jlordo

Reputation: 37813

There are many ways. I prefer:

String url = "http://example.com/files/public_files/test.zip";
String fileName = url.substring(url.lastIndexOf("/") + 1);

Upvotes: 5

Related Questions