首页 Java Java 解析文件后缀名(扩展名)的几种方法

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];
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。