In Java, given a java.net.URL
or a String
in the form of http://www.example.com/some/path/to/a/file.xml
, what is the easiest way to g
If you are using Spring, there is a helper to handle URIs. Here is the solution:
List<String> pathSegments = UriComponentsBuilder.fromUriString(url).build().getPathSegments();
String filename = pathSegments.get(pathSegments.size()-1);
Urls can have parameters in the end, this
/**
* Getting file name from url without extension
* @param url string
* @return file name
*/
public static String getFileName(String url) {
String fileName;
int slashIndex = url.lastIndexOf("/");
int qIndex = url.lastIndexOf("?");
if (qIndex > slashIndex) {//if has parameters
fileName = url.substring(slashIndex + 1, qIndex);
} else {
fileName = url.substring(slashIndex + 1);
}
if (fileName.contains(".")) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
return fileName;
}
If you want to get only the filename from a java.net.URL (not including any query parameters), you could use the following function:
public static String getFilenameFromURL(URL url) {
return new File(url.getPath().toString()).getName();
}
For example, this input URL:
"http://example.com/image.png?version=2&modificationDate=1449846324000"
Would be translated to this output String:
image.png
The Url
object in urllib allows you to access the path's unescaped filename. Here are some examples:
String raw = "http://www.example.com/some/path/to/a/file.xml";
assertEquals("file.xml", Url.parse(raw).path().filename());
raw = "http://www.example.com/files/r%C3%A9sum%C3%A9.pdf";
assertEquals("résumé.pdf", Url.parse(raw).path().filename());
andy's answer redone using split():
Url u= ...;
String[] pathparts= u.getPath().split("\\/");
String filename= pathparts[pathparts.length-1].split("\\.", 1)[0];
create a new file with string image path
String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}