Is there a new Java 8 way of retrieving the file extension?

China☆狼群 提交于 2019-12-04 16:05:05

问题


What I did up until now is following:

String fileName = "file.date.txt";
String ext = fileName.substring(fileName.lastIndexOf('.') + 1);

System.out.printf("'%s'%n", ext); // prints: 'txt'

Is there a more convenient way in Java 8?


回答1:


No, see the changelog of the JDK8 release




回答2:


No there is no more efficient/convenient way in JDK, but many libraries give you ready methods for this, like Guava: Files.getFileExtension(fileName) which wraps your code in single method (with additional validation).




回答3:


Not Java8, but you can always use FilenameUtils.getExtension() from apache Commons library. :)




回答4:


Actually there is a new way of thinking about returning file extensions in Java 8.

Most of the "old" methods described in the other answers return an empty string if there is no extension, but while this avoids NullPointerExceptions, it makes it easy to forget that not all files have an extension. By returning an Optional, you can remind yourself and others about this fact, and you can also make a distinction between file names with an empty extension (dot at the end) and files without extension (no dot in the file name)

public static Optional<String> findExtension(String fileName) {
    int lastIndex = fileName.lastIndexOf('.');
    if (lastIndex == -1) {
        return Optional.empty();
    }
    return Optional.of(fileName.substring(lastIndex + 1));
}



回答5:


Use FilenameUtils.getExtension from Apache Commons IO

Example:

You can provide full path name or only the file name.

String myString1 = FilenameUtils.getExtension("helloworld.exe"); // returns "exe"
String myString2 = FilenameUtils.getExtension("/home/abc/yey.xls"); // returns "xls"

Hope this helps ..



来源:https://stackoverflow.com/questions/30913799/is-there-a-new-java-8-way-of-retrieving-the-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!