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

后端 未结 5 1931
闹比i
闹比i 2021-02-07 06:21

What I did up until now is following:

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

System.out.printf(\         


        
5条回答
  •  既然无缘
    2021-02-07 07:00

    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 findExtension(String fileName) {
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex == -1) {
            return Optional.empty();
        }
        return Optional.of(fileName.substring(lastIndex + 1));
    }
    

提交回复
热议问题