本文主要介绍Java中解析获取文件扩展名(后缀名)的几种方法。

1、使用FilenameUtils.getExtension来获取扩展名

 maven配置:

<dependency>  
<groupId>commons-io</groupId>  
<artifactId>commons-io</artifactId>   
<version>2.4</version>  
</dependency>  
String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); //returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); //returns "exe"

文档:http://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.htm...

2、通过使用lastIndexOf和substring方法来得到扩展名

String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

String extension = "";
int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
if (i > p) {
    extension = fileName.substring(i+1);
}

3、使用Guava库的Files工具类获取扩展名

maven配置:

<dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>17.0</version>
</dependency>
String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt

文档:https://google.github.io/guava/releases/19.0/api/docs/com/google/common/io/Files.html#getFileExtensi...

4、Android上可以使用的方法

String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());

5、经过测试的getExtension获取扩展名方法

public static String getExtension(String fileName) {
    char ch;
    int len;
    if(fileName==null || 
            (len = fileName.length())==0 || 
            (ch = fileName.charAt(len-1))=='/' || ch=='\\' || //in the case of a directory
             ch=='.' ) //in the case of . or ..
        return "";
    int dotInd = fileName.lastIndexOf('.'),
        sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
    if( dotInd<=sepInd )
        return "";
    else
        return fileName.substring(dotInd+1).toLowerCase();
}

测试用例

@Test
public void testGetExtension() {
    assertEquals("", getExtension("C"));
    assertEquals("ext", getExtension("C.ext"));
    assertEquals("ext", getExtension("A/B/C.ext"));
    assertEquals("", getExtension("A/B/C.ext/"));
    assertEquals("", getExtension("A/B/C.ext/.."));
    assertEquals("bin", getExtension("A/B/C.bin"));
    assertEquals("hidden", getExtension(".hidden"));
    assertEquals("dsstore", getExtension("/user/home/.dsstore"));
    assertEquals("", getExtension(".strange."));
    assertEquals("3", getExtension("1.2.3"));
    assertEquals("exe", getExtension("C:\\Program Files (x86)\\java\\bin\\javaw.exe"));
}

6、使用split方法来获取后缀名

  String[] split = fullFileName.split("\\.");
  String ext = split[split.length - 1];