是否有一种新的 Java 8 方法来检索文件扩展名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30913799/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:22:14  来源:igfitidea点击:

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

javafilefile-extension

提问by mike

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?

Java 8 中有更方便的方法吗?

采纳答案by Binkan Salaryman

No, see the changelog of the JDK8 release

没有,看JDK8版本的更新日志

回答by null

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

不是 Java8,但您始终可以FilenameUtils.getExtension()从 apache Commons 库中使用。:)

回答by Pshemo

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).

没有 JDK 中没有更有效/更方便的方法,但是许多库为您提供了现成的方法,例如 Guava:Files.getFileExtension(fileName)它将您的代码包装在单个方法中(带有额外的验证)。

回答by lbalazscs

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

居然还有就是想用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)

如果没有扩展名,其他答案中描述的大多数“旧”方法都会返回一个空字符串,但是虽然这避免了 NullPointerExceptions,但很容易忘记并非所有文件都有扩展名。通过返回一个Optional,你可以提醒自己和其他人这个事实,你也可以区分带有空扩展名的文件名(末尾有点)和没有扩展名的文件(文件名中没有点)

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

回答by Dulith De Costa

Use FilenameUtils.getExtensionfrom Apache Commons IO

使用FilenameUtils.getExtension来自Apache的百科全书IO

Example:

例子:

You can provide full path nameor 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 ..

希望这可以帮助 ..