如何在Java中获取文件的文件扩展名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3571223/
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 get the file extension of a file in Java?
提问by longda
Just to be clear, I'm not looking for the MIME type.
为了清楚起见,我不是在寻找 MIME 类型。
Let's say I have the following input: /path/to/file/foo.txt
假设我有以下输入: /path/to/file/foo.txt
I'd like a way to break this input up, specifically into .txt
for the extension. Is there any built in way to do this in Java? I would like to avoid writing my own parser.
我想要一种方法来分解这个输入,特别.txt
是扩展。在 Java 中是否有任何内置方法可以做到这一点?我想避免编写自己的解析器。
采纳答案by Juan Rojas
In this case, use FilenameUtils.getExtensionfrom Apache Commons IO
在这种情况下,使用FilenameUtils.getExtension从Apache的百科全书IO
Here is an example of how to use it (you may specify either full path or just file name):
以下是如何使用它的示例(您可以指定完整路径或仅指定文件名):
String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"
Maven dependency:
Maven 依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Gradle Groovy DSL
Gradle Groovy DSL
implementation 'commons-io:commons-io:2.6'
Gradle Kotlin DSL
Gradle Kotlin DSL
implementation("commons-io:commons-io:2.6")
Others https://search.maven.org/artifact/commons-io/commons-io/2.6/jar
其他https://search.maven.org/artifact/commons-io/commons-io/2.6/jar
回答by EboMike
Do you really need a "parser" for this?
你真的需要一个“解析器”吗?
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i+1);
}
Assuming that you're dealing with simple Windows-like file names, not something like archive.tar.gz
.
假设您正在处理类似 Windows 的简单文件名,而不是像archive.tar.gz
.
Btw, for the case that a directory may have a '.', but the filename itself doesn't (like /path/to.a/file
), you can do
顺便说一句,对于目录可能有一个“.”,但文件名本身没有(如/path/to.a/file
)的情况,你可以这样做
String extension = "";
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\'));
if (i > p) {
extension = fileName.substring(i+1);
}
回答by longda
// Modified from EboMike's answer
String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));
extension should have ".txt" in it when run.
运行时扩展名应该包含“.txt”。
回答by eee
How about JFileChooser? It is not straightforward as you will need to parse its final output...
JFileChooser 怎么样?这并不简单,因为您需要解析其最终输出...
JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));
which is a MIME type...
这是一种 MIME 类型...
OK...I forget that you don't want to know its MIME type.
好吧...我忘了你不想知道它的 MIME 类型。
Interesting code in the following link: http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
以下链接中的有趣代码:http: //download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
/*
* Get the extension of a file.
*/
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
Related question: How do I trim a file extension from a String in Java?
相关问题: 如何从 Java 中的字符串修剪文件扩展名?
回答by Ninju Bohra
How about (using Java 1.5 RegEx):
怎么样(使用 Java 1.5 RegEx):
String[] split = fullFileName.split("\.");
String ext = split[split.length - 1];
回答by JeanValjean
If you use Guavalibrary, you can resort to Files
utility class. It has a specific method, getFileExtension()
. For instance:
如果您使用Guava库,则可以求助于Files
实用程序类。它有一个特定的方法,getFileExtension()
。例如:
String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt
In addition you may also obtain the filename with a similar function, getNameWithoutExtension():
此外,您还可以使用类似的函数getNameWithoutExtension()获取文件名:
String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo
回答by Olathe
Here's a method that handles .tar.gz
properly, even in a path with dots in directory names:
这是一种可以.tar.gz
正确处理的方法,即使在目录名称中带有点的路径中也是如此:
private static final String getExtension(final String filename) {
if (filename == null) return null;
final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
final int afterLastBackslash = afterLastSlash.lastIndexOf('\') + 1;
final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}
afterLastSlash
is created to make finding afterLastBackslash
quicker since it won't have to search the whole string if there are some slashes in it.
afterLastSlash
创建afterLastBackslash
它是为了更快地查找,因为如果其中有一些斜杠,则不必搜索整个字符串。
The char[]
inside the original String
is reused, adding no garbage there, and the JVM will probably notice that afterLastSlash
is immediately garbage in order to put it on the stack instead of the heap.
char[]
原来的内部String
被重用,没有在那里添加垃圾,JVM 可能afterLastSlash
会立即注意到它是垃圾,以便将它放在堆栈而不是堆上。
回答by shapiy
Just a regular-expression based alternative. Not that fast, not that good.
只是一个基于正则表达式的替代方案。没那么快,也没那么好。
Pattern pattern = Pattern.compile("\.([^.]*)$");
Matcher matcher = pattern.matcher(fileName);
if (matcher.find()) {
String ext = matcher.group(1);
}
回答by Sylvain Leroux
In order to take into account file names without characters beforethe dot, you have to use that slight variation of the accepted answer:
为了考虑点前没有字符的文件名,您必须使用已接受答案的细微变化:
String extension = "";
int i = fileName.lastIndexOf('.');
if (i >= 0) {
extension = fileName.substring(i+1);
}
"file.doc" => "doc"
"file.doc.gz" => "gz"
".doc" => "doc"
回答by Nick Giampietro
Java has a built-in way of dealing with this, in the java.nio.file.Files class, that may work for your needs:
在java.nio.file.Files 类中,Java 有一种内置的方法来处理这个问题,这可能会满足您的需求:
File f = new File("/path/to/file/foo.txt");
String ext = Files.probeContentType(f.toPath());
if(ext.equalsIgnoreCase("txt")) do whatever;
Note that this static method uses the specifications found hereto retrieve "content type," which can vary.
请注意,此静态方法使用此处找到的规范来检索可能会有所不同的“内容类型”。