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
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
This should about cut it (i'll leave the error handling to you):
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
public String getFileNameWithoutExtension(URL url) {
String path = url.getPath();
if (StringUtils.isBlank(path)) {
return null;
}
if (StringUtils.endsWith(path, "/")) {
//is a directory ..
return null;
}
File file = new File(url.getPath());
String fileNameWithExt = file.getName();
int sepPosition = fileNameWithExt.lastIndexOf(".");
String fileNameWithOutExt = null;
if (sepPosition >= 0) {
fileNameWithOutExt = fileNameWithExt.substring(0,sepPosition);
}else{
fileNameWithOutExt = fileNameWithExt;
}
return fileNameWithOutExt;
}
String fileName = url.substring(url.lastIndexOf('/') + 1);
One liner:
new File(uri.getPath).getName
Complete code (in a scala REPL):
import java.io.File
import java.net.URI
val uri = new URI("http://example.org/file.txt?whatever")
new File(uri.getPath).getName
res18: String = file.txt
Note: URI#gePath
is already intelligent enough to strip off query parameters and the protocol's scheme. Examples:
new URI("http://example.org/hey/file.txt?whatever").getPath
res20: String = /hey/file.txt
new URI("hdfs:///hey/file.txt").getPath
res21: String = /hey/file.txt
new URI("file:///hey/file.txt").getPath
res22: String = /hey/file.txt
Here is the simplest way to do it in Android. I know it will not work in Java but It may help Android application developer.
import android.webkit.URLUtil;
public String getFileNameFromURL(String url) {
String fileNameWithExtension = null;
String fileNameWithoutExtension = null;
if (URLUtil.isValidUrl(url)) {
fileNameWithExtension = URLUtil.guessFileName(url, null, null);
if (fileNameWithExtension != null && !fileNameWithExtension.isEmpty()) {
String[] f = fileNameWithExtension.split(".");
if (f != null & f.length > 1) {
fileNameWithoutExtension = f[0];
}
}
}
return fileNameWithoutExtension;
}