在 Java 中修剪后缀最有效的方法是什么,像下面这样:
title part1.txt title part2.html => title part1 title part2
str.substring(0, str.lastIndexOf('.'))
String foo = "title part1.txt"; foo = foo.substring(0, foo.lastIndexOf('.'));
我会这样做:
String title_part = "title part1.txt"; int i; for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--); title_part = title_part.substring(0,i);
从头到尾直到“ .”,然后调用子字符串。
String fileName="foo.bar"; int dotIndex=fileName.lastIndexOf('.'); if(dotIndex>=0) { // to prevent exception if there is no dot fileName=fileName.substring(0,dotIndex); }
这是个陷阱问题吗
我想不出更快的方法了。
这种代码我们不应该自己做。使用图书馆处理日常事务,把你的大脑留给困难的事情。
在这种情况下,我建议使用 Apache Commons IO中的 RemoveExtension ()
由于在一行程序中使用 String.substring和 String.lastIndex是好的,所以在能够处理某些文件路径方面存在一些问题。
String.substring
String.lastIndex
以下面的路径为例:
a.b/c
使用一行程序将导致:
a
不是这样的。
结果应该是 c,但是由于文件没有扩展名,但是路径的目录名中有一个 .,一行程序方法被欺骗,将路径的一部分作为文件名给出,这是不正确的。
c
.
需要支票
受到 斯卡夫曼的回答的启发,我研究了 Apache Commons IO的 FilenameUtils.removeExtension方法。
FilenameUtils.removeExtension
为了重新创建它的行为,我编写了一些新方法应该完成的测试,它们是:
Path Filename -------------- -------- a/b/c c a/b/c.jpg c a/b/c.jpg.jpg c.jpg a.b/c c a.b/c.jpg c a.b/c.jpg.jpg c.jpg c c c.jpg c c.jpg.jpg c.jpg
(这就是我检查的全部内容——可能还有其他一些我没有注意到的检查。)
执行
以下是我对 removeExtension方法的实现:
removeExtension
public static String removeExtension(String s) { String separator = System.getProperty("file.separator"); String filename; // Remove the path upto the filename. int lastSeparatorIndex = s.lastIndexOf(separator); if (lastSeparatorIndex == -1) { filename = s; } else { filename = s.substring(lastSeparatorIndex + 1); } // Remove the extension. int extensionIndex = filename.lastIndexOf("."); if (extensionIndex == -1) return filename; return filename.substring(0, extensionIndex); }
用上面的测试运行这个 removeExtension方法会得到上面列出的结果。
该方法使用以下代码进行了测试。由于这是在 Windows 上运行的,所以路径分隔符是 \,当作为 String文本的一部分使用时,必须使用 \转义它。
\
String
System.out.println(removeExtension("a\\b\\c")); System.out.println(removeExtension("a\\b\\c.jpg")); System.out.println(removeExtension("a\\b\\c.jpg.jpg")); System.out.println(removeExtension("a.b\\c")); System.out.println(removeExtension("a.b\\c.jpg")); System.out.println(removeExtension("a.b\\c.jpg.jpg")); System.out.println(removeExtension("c")); System.out.println(removeExtension("c.jpg")); System.out.println(removeExtension("c.jpg.jpg"));
结果是:
c c c.jpg c c c.jpg c c c.jpg
结果是预期的结果概述的测试方法应该实现。
我发现 酷鸟的回答特别有用。
但我把最后的结果语句改成了:
if (extensionIndex == -1) return s; return s.substring(0, lastSeparatorIndex+1) + filename.substring(0, extensionIndex);
因为我希望返回完整的路径名。
So "C:\Users\mroh004.COM\Documents\Test\Test.xml" becomes "C:\Users\mroh004.COM\Documents\Test\Test" and not "Test"
顺便说一下,在我的例子中,当我想要一个快速的解决方案来删除一个特定的扩展时,我大致是这样做的:
if (filename.endsWith(ext)) return filename.substring(0,filename.length() - ext.length()); else return filename;
filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();
String[] splitted = fileName.split("."); String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");
用字符串图像路径创建一个新文件
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 ""; } }
文件/ org.apache.commons.io 实用程序2.4版给出了以下答案
public static String removeExtension(String filename) { if (filename == null) { return null; } int index = indexOfExtension(filename); if (index == -1) { return filename; } else { return filename.substring(0, index); } } public static int indexOfExtension(String filename) { if (filename == null) { return -1; } int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR); int lastSeparator = indexOfLastSeparator(filename); return lastSeparator > extensionPos ? -1 : extensionPos; } public static int indexOfLastSeparator(String filename) { if (filename == null) { return -1; } int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR); int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR); return Math.max(lastUnixPos, lastWindowsPos); } public static final char EXTENSION_SEPARATOR = '.'; private static final char UNIX_SEPARATOR = '/'; private static final char WINDOWS_SEPARATOR = '\\';
private String trimFileExtension(String fileName) { String[] splits = fileName.split( "\\." ); return StringUtils.remove( fileName, "." + splits[splits.length - 1] ); }
使用正则表达式。这个代替最后一个点,以及它之后的所有内容。
String baseName = fileName.replaceAll("\\.[^.]*$", "");
如果要预编译正则表达式,还可以创建模式对象。
请记住没有文件扩展名或有多个文件扩展名的情况
示例文件名: file | file.txt | file.tar.bz2
/** * * @param fileName * @return file extension * example file.fastq.gz => fastq.gz */ private String extractFileExtension(String fileName) { String type = "undefined"; if (FilenameUtils.indexOfExtension(fileName) != -1) { String fileBaseName = FilenameUtils.getBaseName(fileName); int indexOfExtension = -1; while (fileBaseName.contains(".")) { indexOfExtension = FilenameUtils.indexOfExtension(fileBaseName); fileBaseName = FilenameUtils.getBaseName(fileBaseName); } type = fileName.substring(indexOfExtension + 1, fileName.length()); } return type; }
如果您的项目已经依赖于 Google 核心库,请在 com.google.common.io.Files类中使用方法。您需要的方法是 getNameWithoutExtension。
com.google.common.io.Files
getNameWithoutExtension
你可以试试这个函数,非常简单
public String getWithoutExtension(String fileFullPath){ return fileFullPath.substring(0, fileFullPath.lastIndexOf('.')); }
String img = "example.jpg"; // String imgLink = "http://www.example.com/example.jpg"; URI uri = null; try { uri = new URI(img); String[] segments = uri.getPath().split("/"); System.out.println(segments[segments.length-1].split("\\.")[0]); } catch (Exception e) { e.printStackTrace(); }
这将输出 IMG和 ImgLink的 例子
public static String removeExtension(String file) { if(file != null && file.length() > 0) { while(file.contains(".")) { file = file.substring(0, file.lastIndexOf('.')); } } return file; }
如果你使用 Spring,你可以使用
org.springframework.util.StringUtils.stripFilenameExtension(String path)
从指定的 Java 资源路径中删除文件扩展名,例如。 “ mypath/myfile.txt”-> “ mypath/myfile”。 路径-文件路径 返回: 带剥离文件扩展名的路径
从指定的 Java 资源路径中删除文件扩展名,例如。
“ mypath/myfile.txt”-> “ mypath/myfile”。
路径-文件路径
返回: 带剥离文件扩展名的路径
为了坚持使用 Path 类,我能写出的最好的东西是:
Path removeExtension(Path path) { return path.resolveSibling(path.getFileName().toString().replaceFirst("\\.[^.]*$", "")); }
private String trimFileName(String fileName) { String[] ext; ext = fileName.split("\\."); return fileName.replace(ext[ext.length - 1], ""); }
这段代码将把文件名拆分成各个部分,为例。如果文件名是 File-name. hello.txt,那么它将被拆分成字符串数组,如{“ file-name”,“ hello”,“ txt”}。所以无论如何,这个字符串数组中的最后一个元素将是这个特定文件的文件扩展名,所以我们可以简单地用 arrayname.length - 1找到任何数组中的最后一个元素,所以在我们知道最后一个元素之后,我们可以在文件名中用一个空字符串替换文件扩展名。最后,这将返回 file-name。你好。,如果你想删除最后一个句点,那么你可以添加只有句点的字符串到返回行中字符串数组的最后一个元素。看起来像是,
arrayname.length - 1
return fileName.replace("." + ext[ext.length - 1], "");
伙计们,不要给自己太大的压力。我已经说过很多次了。只需将此公共静态方法复制粘贴到 staticUtils 库中,以备将来使用; -)
static String removeExtension(String path){ String filename; String foldrpath; String filenameWithoutExtension; if(path.equals("")){return "";} if(path.contains("\\")){ // direct substring method give wrong result for "a.b.c.d\e.f.g\supersu" filename = path.substring(path.lastIndexOf("\\")); foldrpath = path.substring(0, path.lastIndexOf('\\'));; if(filename.contains(".")){ filenameWithoutExtension = filename.substring(0, filename.lastIndexOf('.')); }else{ filenameWithoutExtension = filename; } return foldrpath + filenameWithoutExtension; }else{ return path.substring(0, path.lastIndexOf('.')); } }