在Java中,给定a java.net.URL
或a String
形式http://www.example.com/some/path/to/a/file.xml
,获取文件名的最简单方法是什么,减去扩展名?所以,在这个例子中,我正在寻找返回的东西"file"
.
我可以想到几种方法来做到这一点,但我正在寻找一些易于阅读和简短的方法.
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() ); String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
如何使用Apache commons-io而不是重新发明轮子:
import org.apache.commons.io.FilenameUtils; public class FilenameUtilTest { public static void main(String[] args) throws Exception { URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test"); System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml } }
这应该削减它(我会留下错误处理给你):
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); }
如果你不需要摆脱文件扩展名,那么这是一种方法,不需要使用容易出错的字符串操作而不使用外部库.适用于Java 1.7+:
import java.net.URI import java.nio.file.Paths String url = "http://example.org/file?p=foo&q=bar" String filename = Paths.get(new URI(url).getPath()).getFileName().toString()
public static String getFileName(URL extUrl) { //URL: "http://photosaaaaa.net/photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg" String filename = ""; //PATH: /photos-ak-snc1/v315/224/13/659629384/s659629384_752969_4472.jpg String path = extUrl.getPath(); //Checks for both forward and/or backslash //NOTE:**While backslashes are not supported in URL's //most browsers will autoreplace them with forward slashes //So technically if you're parsing an html page you could run into //a backslash , so i'm accounting for them here; String[] pathContents = path.split("[\\\\/]"); if(pathContents != null){ int pathContentsLength = pathContents.length; System.out.println("Path Contents Length: " + pathContentsLength); for (int i = 0; i < pathContents.length; i++) { System.out.println("Path " + i + ": " + pathContents[i]); } //lastPart: s659629384_752969_4472.jpg String lastPart = pathContents[pathContentsLength-1]; String[] lastPartContents = lastPart.split("\\."); if(lastPartContents != null && lastPartContents.length > 1){ int lastPartContentLength = lastPartContents.length; System.out.println("Last Part Length: " + lastPartContentLength); //filenames can contain . , so we assume everything before //the last . is the name, everything after the last . is the //extension String name = ""; for (int i = 0; i < lastPartContentLength; i++) { System.out.println("Last Part " + i + ": "+ lastPartContents[i]); if(i < (lastPartContents.length -1)){ name += lastPartContents[i] ; if(i < (lastPartContentLength -2)){ name += "."; } } } String extension = lastPartContents[lastPartContentLength -1]; filename = name + "." +extension; System.out.println("Name: " + name); System.out.println("Extension: " + extension); System.out.println("Filename: " + filename); } } return filename; }
获取带扩展名的文件名,不带扩展名,仅使用3行扩展名:
String urlStr = "http://www.example.com/yourpath/foler/test.png"; String fileName = urlStr.substring(urlStr.lastIndexOf('/')+1, urlStr.length()); String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.')); String fileExtension = urlStr.substring(urlStr.lastIndexOf(".")); Log.i("File Name", fileName); Log.i("File Name Without Extension", fileNameWithoutExtension); Log.i("File Extension", fileExtension);
记录结果:
File Name(13656): test.png File Name Without Extension(13656): test File Extension(13656): .png
希望它会对你有所帮助.
我想出来了:
String url = "http://www.example.com/some/path/to/a/file.xml"; String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));
一个班轮:
new File(uri.getPath).getName
完整代码:
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
注意:URI#gePath
已经足够智能去除查询参数和协议的方案.例子:
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
把事情简单化 :
/** * This function will take an URL as input and return the file name. *Examples :
*
String fileName = url.substring(url.lastIndexOf('/') + 1);
这是在Android中执行此操作的最简单方法.我知道它不适用于Java,但它可能有助于Android应用程序开发人员.
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; }