1

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'
1

4 Answers 4

5

There are many ways. I prefer:

String url = "http://example.com/files/public_files/test.zip";
String fileName = url.substring(url.lastIndexOf("/") + 1);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

You have to handle the MalformedURLException, and this actually returns /files/public_files/test.zip
@jlordo. Too bad. There is no method to get the file name. :(
@jlordo. Found one in Apache Commons. :)
0

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];

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.