如何在Java中获取没有扩展名的文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/924394/
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 to get the filename without the extension in Java?
提问by Iso
Can anyone tell me how to get the filename without the extension? Example:
谁能告诉我如何获取没有扩展名的文件名?例子:
fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
采纳答案by Ulf Lindback
If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in nullor dots in the path but not in the filename, you can use the following:
如果你像我一样,宁愿使用一些他们可能已经想到所有特殊情况的库代码,例如如果你在路径中传入null或点而不是在文件名中会发生什么,你可以使用以下内容:
import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
回答by paxdiablo
See the following test program:
看下面的测试程序:
public class javatemp {
static String stripExtension (String str) {
// Handle null case specially.
if (str == null) return null;
// Get position of last '.'.
int pos = str.lastIndexOf(".");
// If there wasn't any '.' just return the string as is.
if (pos == -1) return str;
// Otherwise return the string, up to the dot.
return str.substring(0, pos);
}
public static void main(String[] args) {
System.out.println ("test.xml -> " + stripExtension ("test.xml"));
System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
System.out.println ("test -> " + stripExtension ("test"));
System.out.println ("test. -> " + stripExtension ("test."));
}
}
which outputs:
输出:
test.xml -> test
test.2.xml -> test.2
test -> test
test. -> test
回答by brianegge
The easiest way is to use a regular expression.
最简单的方法是使用正则表达式。
fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.
上面的表达式将删除最后一个点后跟一个或多个字符。这是一个基本的单元测试。
public void testRegex() {
assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
回答by Dan J
While I am a big believer in reusing libraries, the org.apache.commons.io JARis 174KB, which is noticably large for a mobile app.
虽然我非常相信重用库,但org.apache.commons.io JAR有 174KB,这对于移动应用程序来说非常大。
If you download the source code and take a look at their FilenameUtils class, you can see there are a lot of extra utilities, and it does cope with Windows and Unix paths, which is all lovely.
如果您下载源代码并查看它们的 FilenameUtils 类,您会发现有很多额外的实用程序,并且它确实可以处理 Windows 和 Unix 路径,这一切都很可爱。
However, if you just want a couple of static utility methods for use with Unix style paths (with a "/" separator), you may find the code below useful.
但是,如果您只想要几个用于 Unix 样式路径(带有“/”分隔符)的静态实用程序方法,您可能会发现下面的代码很有用。
The removeExtension
method preserves the rest of the path along with the filename. There is also a similar getExtension
.
该removeExtension
方法保留路径的其余部分以及文件名。还有一个类似的getExtension
。
/**
* Remove the file extension from a filename, that may include a path.
*
* e.g. /path/to/myfile.jpg -> /path/to/myfile
*/
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);
}
}
/**
* Return the file extension from a filename, including the "."
*
* e.g. /path/to/myfile.jpg -> .jpg
*/
public static String getExtension(String filename) {
if (filename == null) {
return null;
}
int index = indexOfExtension(filename);
if (index == -1) {
return filename;
} else {
return filename.substring(index);
}
}
private static final char EXTENSION_SEPARATOR = '.';
private static final char DIRECTORY_SEPARATOR = '/';
public static int indexOfExtension(String filename) {
if (filename == null) {
return -1;
}
// Check that no directory separator appears after the
// EXTENSION_SEPARATOR
int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
int lastDirSeparator = filename.lastIndexOf(DIRECTORY_SEPARATOR);
if (lastDirSeparator > extensionPos) {
LogIt.w(FileSystemUtil.class, "A directory separator appears after the file extension, assuming there is no file extension");
return -1;
}
return extensionPos;
}
回答by Sksoni
Try the code below. Using core Java basic functions. It takes care of String
s with extension, and without extension (without the '.'
character). The case of multiple '.'
is also covered.
试试下面的代码。使用核心 Java 基本功能。它处理String
带扩展名和不带扩展名(不带'.'
字符)的s 。'.'
也涵盖了多个的情况。
String str = "filename.xml";
if (!str.contains("."))
System.out.println("File Name=" + str);
else {
str = str.substring(0, str.lastIndexOf("."));
// Because extension is always after the last '.'
System.out.println("File Name=" + str);
}
You can adapt it to work with null
strings.
您可以调整它以使用null
字符串。
回答by Jonik
If your project uses Guava(14.0 or newer), you can go with Files.getNameWithoutExtension()
.
如果您的项目使用Guava(14.0 或更高版本),您可以使用Files.getNameWithoutExtension()
.
(Essentially the same as FilenameUtils.removeExtension()
from Apache Commons IO, as the highest-voted answersuggests. Just wanted to point out Guava does this too. Personally I didn't want to add dependency to Commons—which I feel is a bit of a relic—just because of this.)
(本质上与FilenameUtils.removeExtension()
来自 Apache Commons IO的相同,正如投票最高的答案所暗示的那样。只是想指出 Guava 也是这样做的。就我个人而言,我不想添加对 Commons 的依赖——我觉得这有点像遗物——只是因为这个。)
回答by Om.
Here is the consolidated list order by my preference.
这是我偏好的综合列表顺序。
Using apache commons
使用 apache 公共资源
import org.apache.commons.io.FilenameUtils;
String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
OR
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
Using Google Guava (If u already using it)
使用谷歌番石榴(如果你已经在使用它)
import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);
Or using Core Java
或者使用核心 Java
1)
1)
String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
fileName = fileName.substring(0, pos);
}
2)
2)
if (fileName.indexOf(".") > 0) {
return fileName.substring(0, fileName.lastIndexOf("."));
} else {
return fileName;
}
3)
3)
private static final Pattern ext = Pattern.compile("(?<=.)\.[^.]+$");
public static String getFileNameWithoutExtension(File file) {
return ext.matcher(file.getName()).replaceAll("");
}
Liferay API
Liferay API
import com.liferay.portal.kernel.util.FileUtil;
String fileName = FileUtil.stripExtension(file.getName());
回答by David Cheung
Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java
以下是来自https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java 的参考
/**
* Gets the base name, without extension, of given file name.
* <p/>
* e.g. getBaseName("file.txt") will return "file"
*
* @param fileName
* @return the base name
*/
public static String getBaseName(String fileName) {
int index = fileName.lastIndexOf('.');
if (index == -1) {
return fileName;
} else {
return fileName.substring(0, index);
}
}
回答by Hamzeh Soboh
If you don't like to import the full apache.commons, I've extracted the same functionality:
如果您不喜欢导入完整的 apache.commons,我已经提取了相同的功能:
public class StringUtils {
public static String getBaseName(String filename) {
return removeExtension(getName(filename));
}
public static int indexOfLastSeparator(String filename) {
if(filename == null) {
return -1;
} else {
int lastUnixPos = filename.lastIndexOf(47);
int lastWindowsPos = filename.lastIndexOf(92);
return Math.max(lastUnixPos, lastWindowsPos);
}
}
public static String getName(String filename) {
if(filename == null) {
return null;
} else {
int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
}
public static String removeExtension(String filename) {
if(filename == null) {
return null;
} else {
int index = indexOfExtension(filename);
return index == -1?filename:filename.substring(0, index);
}
}
public static int indexOfExtension(String filename) {
if(filename == null) {
return -1;
} else {
int extensionPos = filename.lastIndexOf(46);
int lastSeparator = indexOfLastSeparator(filename);
return lastSeparator > extensionPos?-1:extensionPos;
}
}
}
回答by Peter S.
You can split it by "." and on index 0 is file name and on 1 is extension, but I would incline for the best solution with FileNameUtils from apache.commons-io like it was mentioned in the first article. It does not have to be removed, but sufficent is:
你可以用“.”分割它。索引 0 是文件名,1 是扩展名,但我倾向于使用来自 apache.commons-io 的 FileNameUtils 的最佳解决方案,就像第一篇文章中提到的那样。它不必被删除,但足够的是:
String fileName = FilenameUtils.getBaseName("test.xml");
String fileName = FilenameUtils.getBaseName("test.xml");