问题
I am trying to extract a file name with some specific extension from a URL. For example, I have a URL like "https://abc.xyz.com/path/somefilename.xy". I need to extract "somefilename.xy" from the above URL, and nothing else.
basically I need to write that code in my java program
I am not that good in regular expressions, so can somebody help me in that.
回答1:
You could also do it without regular expressions like so:
String url = "https://abc.xyz.com/path/somefilename.xy";
String fileName = url.substring(url.lastIndexOf('/') + 1);
// fileName is now "somefilename.xy"
EDIT (credit to @SomethingSomething): If you should also support urls with parameters, like https://abc.xyz.com/path/somefilename.xy?param1=blie¶m2=bla, you could use this instead:
String url = "https://abc.xyz.com/path/somefilename.xy?param1=blie¶m2=bla";
java.net.Url urlObj = new java.net.Url(url);
String urlPath = urlObj.getPath();
String fileName = urlPath.substring(urlPath.lastIndexOf('/') + 1);
// fileName is now "somefilename.xy"
回答2:
This has been done a hundred times, taken from this answer:
import org.apache.commons.io.FilenameUtils;
public class FilenameUtilTest {
public static void main(String[] args) {
String url = "http://www.example.com/some/path/to/a/file.xml";
String baseName = FilenameUtils.getBaseName(url);
String extension = FilenameUtils.getExtension(url);
System.out.println("Basename : " + baseName);
System.out.println("extension : " + extension);
}
}
来源:https://stackoverflow.com/questions/26508424/need-to-extract-filename-from-url