如何从 Java 中的字符串修剪文件扩展名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/941272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I trim a file extension from a String in Java?
提问by omg
What's the most efficient way to trim the suffix in Java, like this:
在 Java 中修剪后缀的最有效方法是什么,如下所示:
title part1.txt
title part2.html
=>
title part1
title part2
回答by Svitlana Maksymchuk
str.substring(0, str.lastIndexOf('.'))
回答by Jherico
String foo = "title part1.txt";
foo = foo.substring(0, foo.lastIndexOf('.'));
回答by fmsf
I would do like this:
我会这样做:
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);
Starting to the end till the '.' then call substring.
开始到结束直到'.' 然后调用子串。
Edit: Might not be a golf but it's effective :)
编辑:可能不是高尔夫,但它很有效:)
回答by Huxi
String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
fileName=fileName.substring(0,dotIndex);
}
Is this a trick question? :p
这是一个技巧问题吗?:p
I can't think of a faster way atm.
我想不出更快的方式自动取款机。
回答by skaffman
This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff.
这是我们不应该自己做的那种代码。把图书馆用于平凡的东西,把你的大脑留给困难的东西。
In this case, I recommend using FilenameUtils.removeExtension()from Apache Commons IO
在这种情况下,我建议使用FilenameUtils.removeExtension()从Apache的百科全书IO
回答by coobird
As using the String.substring
and String.lastIndex
in a one-liner is good, there are some issues in terms of being able to cope with certain file paths.
由于在单行中使用String.substring
和String.lastIndex
是好的,因此在能够处理某些文件路径方面存在一些问题。
Take for example the following path:
以以下路径为例:
a.b/c
Using the one-liner will result in:
使用 one-liner 将导致:
a
That's incorrect.
那是不正确的。
The result should have been c
, but since the file lacked an extension, but the path had a directory with a .
in the name, the one-liner method was tricked into giving part of the path as the filename, which is not correct.
结果应该是c
,但是由于文件没有扩展名,但是路径中有一个.
名称中带有 a 的目录,单行方法被欺骗,将路径的一部分作为文件名,这是不正确的。
Need for checks
需要检查
Inspired by skaffman's answer, I took a look at the FilenameUtils.removeExtension
method of the Apache Commons IO.
受skaffman的回答启发,我看了一下Apache Commons IO的FilenameUtils.removeExtension
方法。
In order to recreate its behavior, I wrote a few tests the new method should fulfill, which are the following:
为了重新创建它的行为,我编写了一些新方法应该完成的测试,如下所示:
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
(And that's all I've checked for -- there probably are other checks that should be in place that I've overlooked.)
(这就是我检查过的全部内容——可能还有其他我忽略的检查应该到位。)
The implementation
实施
The following is my implementation for the removeExtension
method:
以下是我对该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);
}
Running this removeExtension
method with the above tests yield the results listed above.
removeExtension
使用上述测试运行此方法会产生上面列出的结果。
The method was tested with the following code. As this was run on Windows, the path separator is a \
which must be escaped with a \
when used as part of a String
literal.
该方法已使用以下代码进行测试。由于这是在 Windows 上运行的,路径分隔符是 a \
,\
当用作String
文字的一部分时,必须用 a 转义。
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"));
The results were:
结果是:
c
c
c.jpg
c
c
c.jpg
c
c
c.jpg
The results are the desired results outlined in the test the method should fulfill.
结果是方法应满足的测试中概述的所需结果。
回答by mxro
I found coolbird's answerparticularly useful.
我发现coolbird的回答特别有用。
But I changed the last result statements to:
但是我将最后的结果语句更改为:
if (extensionIndex == -1)
return s;
return s.substring(0, lastSeparatorIndex+1)
+ filename.substring(0, extensionIndex);
as I wanted the full path name to be returned.
因为我希望返回完整的路径名。
So "C:\Users\mroh004.COM\Documents\Test\Test.xml" becomes "C:\Users\mroh004.COM\Documents\Test\Test" and not "Test"
回答by Edward Falk
BTW, in my case, when I wanted a quick solution to remove a specific extension, this is approximately what I did:
顺便说一句,就我而言,当我想要一个快速解决方案来删除特定扩展名时,这大约是我所做的:
if (filename.endsWith(ext))
return filename.substring(0,filename.length() - ext.length());
else
return filename;
回答by Alexander
filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();
回答by Mahdak
String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");