如何在 Java 中获取文件的文件扩展名?

How do I get the file extension of a file in Java?

提问人:longda 提问时间:8/26/2010 最后编辑:longda 更新时间:11/4/2022 访问量:849134

问:

需要明确的是,我不是在寻找MIME类型。

假设我有以下输入:/path/to/file/foo.txt

我想要一种方法来分解这个输入,特别是用于扩展。Java 中是否有任何内置方法可以做到这一点?我想避免编写自己的解析器。.txt

Java 文件 IO

评论

15赞 ArtOfWarfare 11/20/2013
你永远不知道什么时候会出现一些新平台,将扩展定义为用逗号分隔。现在,您需要编写与平台相关的代码。Java 框架应该更具前瞻性,并具有用于获取扩展的 API,它们编写依赖于平台的代码,而您作为 API 的用户,只需说获取扩展即可。
0赞 Eric Duminil 11/29/2019
@ArtOfWarfare:我的天啊。让我们创建一个包含数千个类的 100MB JRE,但请确保不要实现任何返回的方法,因为某个平台可能想要使用。"txt""filename.txt""filename,txt"
0赞 VelocityPulse 3/17/2020
@EricDuminil “确保不要实现任何从”filename.txt“返回”txt“的方法”???尝试。。。。。是的..他们肯定不会无缘无故地复制一些东西......path.substring(path.lastIndexOf("."));
0赞 Eric Duminil 3/18/2020
@VelocityPulse这正是困扰我的地方。由于没有获取文件扩展名的标准方法,因此您会得到数十个半错误的答案和略有不同的实现。您的代码使用了 2 个方法(我本来希望有一个单一的显式方法),它返回 ,这可能不是所需的结果,最糟糕的是,如果没有扩展名,它会失败而不是返回空字符串。".txt""filename.txt"StringIndexOutOfBoundsException
0赞 Nikolas Charalambidis 11/4/2022
最后,从 Java 20 开始,JDK 中提供了一种新方法:stackoverflow.com/a/74315488/3764965Path#getExtension

答:

371赞 EboMike 8/26/2010 #1

你真的需要一个“解析器”吗?

String extension = "";

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

假设您正在处理简单的类似 Windows 的文件名,而不是类似 .archive.tar.gz

顺便说一句,如果目录可能有“.”,但文件名本身没有(如),您可以这样做/path/to.a/file

String extension = "";

int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));

if (i > p) {
    extension = fileName.substring(i+1);
}

评论

4赞 longda 8/26/2010
谢谢!当然,您可能需要一个解析器/对象,如果您想进行更多的操作而不仅仅是扩展......比如说,如果你只想要路径、父目录、文件名(减去扩展名)等。我来自 C# 和 .Net,我们有这个:msdn.microsoft.com/en-us/library/......
14赞 Tyler 8/26/2010
正如您所说,除了使用幼稚的 lastIndexOf(“.”) 之外,还有很多事情需要考虑。我猜 Apache Commons 有一种方法,它考虑了所有棘手的潜在问题。
13赞 Pijusn 7/6/2013
我认为应该改为 or .这将处理像 .i > 0i >= 0i != -1.htaccess
14赞 Don Cheadle 2/14/2015
无论任何代码片段多么简单......你仍然需要更新它/维护它/测试它/让它作为一个方便的依赖项可用......如果已经有一个库在做所有这些工作,那就容易多了
2赞 tgkprog 7/6/2015
更棘手的是,如果文件以点结尾。在库中更好。if (i > p && i < (fileName.length()-1)) { extension = fileName.substring(i+1);
3赞 longda 8/26/2010 #2
// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

扩展在运行时应该有“.txt”。

评论

13赞 EboMike 8/26/2010
如果名称没有扩展名,则会崩溃。
4赞 eee 8/26/2010 #3

JFileChooser怎么样?这并不简单,因为您需要解析其最终输出......

JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));

这是一个MIME类型...

还行。。。我忘了你不想知道它的MIME类型。

以下链接中的有趣代码:http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

/*
 * Get the extension of a file.
 */  
public static String getExtension(File f) {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');

    if (i > 0 &&  i < s.length() - 1) {
        ext = s.substring(i+1).toLowerCase();
    }
    return ext;
}

相关问题:如何在 Java 中从 String 修剪文件扩展名?

8赞 Ninju Bohra 4/11/2013 #4

怎么样(使用 Java 1.5 正则表达式):

    String[] split = fullFileName.split("\\.");
    String ext = split[split.length - 1];
88赞 JeanValjean 4/13/2013 #5

如果您使用 Guava 库,您可以求助于文件实用程序类。它有一个特定的方法,getFileExtension()。例如:

String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt

此外,您还可以使用类似的函数 getNameWithoutExtension() 获取文件名:

String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo

评论

4赞 JeanValjean 6/12/2013
真?这是一个很棒的图书馆,充满了实用程序。它们中的大多数将成为 Java8 的一部分,就像伟大的 Guava 函数一样。
0赞 Lluis Martinez 1/30/2014
不幸的是,并非所有人都能决定使用哪些库。至少我们有Apache Commons,尽管是一个旧的。
1赞 Al-Mothafar 1/13/2019
如果你看到源代码,实际上它没什么大不了的。另外,请注意,由于某种原因标记为“不稳定”。getFileExtensionint dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1)Files
1赞 JeanValjean 1/15/2019
@Al-Mothafar 很多类都被标记为不稳定(参见多地图构建器),我也不明白为什么:已经发布了几个,但那里没有任何变化。
4赞 Olathe 4/14/2013 #6

下面是一个正确处理的方法,即使在目录名称中带有点的路径中也是如此:.tar.gz

private static final String getExtension(final String filename) {
  if (filename == null) return null;
  final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
  final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
  final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
  return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}

afterLastSlash创建是为了加快查找速度,因为如果其中有一些斜杠,则不必搜索整个字符串。afterLastBackslash

原来的内部是重用的,没有添加任何垃圾,JVM 可能会注意到 afterLastSlash 立即成为垃圾,以便将其放在堆栈而不是堆上char[]String

评论

0赞 humazed 6/1/2016
这个方法是从番石榴源码复制而来的,你必须提到这一点。
1赞 Olathe 6/1/2016
我没有复制这个。如果它在 Guava 源代码中,他们从这里复制了它。也许通知他们。
0赞 humazed 6/1/2016
对不起,顺便说一句,它并不完全相同,所以愿你和 Guava 开发人员有同样的想法。
2赞 intrepidis 2/15/2018
实际上,“gz”是要返回的正确扩展名。如果调用代码也可以处理“tar”,那么它应该额外检查函数外部。如果用户的文件名是,则此方法将返回错误的扩展名。getExtension"my zip. don't touch.tar.gz"
742赞 Juan Rojas 4/25/2013 #7

在这种情况下,请使用 Apache Commons IO 中的 FilenameUtils.getExtension

以下是如何使用它的示例(您可以指定完整路径或仅指定文件名):

import org.apache.commons.io.FilenameUtils;

// ...

String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"

Maven 依赖:

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

Gradle Groovy DSL

implementation 'commons-io:commons-io:2.6'

Gradle Kotlin DSL

implementation("commons-io:commons-io:2.6")

其他人 https://search.maven.org/artifact/commons-io/commons-io/2.6/jar

评论

75赞 Zitrax 4/23/2014
应该注意的是,它只为名为 archive.tar.gz 的文件返回“gz”。
120赞 BrainSlugs83 4/22/2015
@Zitrax那是因为“gz”是文件扩展名。
33赞 cirovladimir 3/28/2016
@zhelon .gz 代表 GNU 压缩文件,.tar 代表 (t)ape (ar)chive。所以.tar.gz 是 gnu zipped 文件中的 tar 文件,它的扩展名为 .gz。
2赞 scadge 10/11/2016
@guru_001 不,当然不是,只是提到您可以使用完整路径或仅文件名来调用它。
1赞 user25 2/25/2018
@Zitrax包含点的文件或扩展名不能有多个扩展名,因此在您的情况下,扩展名.gz
0赞 shapiy 5/13/2013 #8

只是一个基于正则表达式的替代方案。没那么快,没那么好。

Pattern pattern = Pattern.compile("\\.([^.]*)$");
Matcher matcher = pattern.matcher(fileName);

if (matcher.find()) {
    String ext = matcher.group(1);
}
16赞 Sylvain Leroux 9/11/2013 #9

为了考虑点没有字符的文件名,您必须使用已接受答案的细微变化:

String extension = "";

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

"file.doc" => "doc"
"file.doc.gz" => "gz"
".doc" => "doc"

评论

0赞 chrisinmtown 8/13/2018
可能应该保护自己免受“foo.”输入的影响。
111赞 luke1985 2/24/2014 #10
private String getFileExtension(File file) {
    String name = file.getName();
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf);
}

评论

14赞 NickEntin 11/17/2014
应该注意的是,这也返回了“.”,因此您的文件扩展名将是“.txt”,而不是其他一些答案中的“txt”
2赞 Hanzallah Afgan 5/3/2015
更好的答案和@NickEntin更好的评论。要从文件的扩展名中删除句点 “.”,可以编码为 int lastIndexOf = name.lastIndexOf(“.”) + 1;
16赞 Iman Akbari 7/16/2015
这种方法在某些情况下可能不起作用,例如 /usr/bin/foo.bar/httpconf
8赞 Iman Akbari 8/5/2015
@lukasz1985 1.数以百计的 Linux 软件包使用类似“init.d”的名称创建目录,此外,依赖没有带点目录的路径是不安全的,因为它不是非法的 2.我正在为 Android 编码,所以我使用了一些我不记得的 SDK 方法,但我想 stackoverflow.com/a/3571239/2546146 没有这个缺陷
6赞 Dreamspace President 7/22/2017
@Iman Akbari:getName() 仅返回文件名本身,在您的示例中为“httpconf”。
12赞 Ebrahim Byagowi 3/14/2014 #11

我的肮脏和可能最小的使用 String.replaceAll

.replaceAll("^.*\\.(.*)$", "$1")

请注意,首先是贪婪的,因此它会尽可能地抓取大多数可能的字符,然后只剩下最后一个点和文件扩展名。*

评论

0赞 Zack 9/22/2017
如果文件没有扩展名,则此操作将失败。
0赞 Ebrahim Byagowi 9/24/2017
是的,不幸的是,仍然可以用于简单的场景,例如快速文件类型检测,例如具有不正确的扩展名与没有扩展名没有太大区别,或者当替换结果等于输入时,可以放置 if 条件。
2赞 Ebrahim Byagowi 9/24/2017
甚至更短.replaceAll(".*\\.", "")
8赞 Geng Jiawen 6/10/2014 #12

如果你打算使用Apache commons-io,并且只想检查文件的扩展名然后做一些操作,你可以使用它,这里有一个片段:

if(FilenameUtils.isExtension(file.getName(),"java")) {
    someoperation();
}

评论

0赞 Babken Vardanyan 3/30/2016
请注意,根据文档,此检查区分大小写。
27赞 intrepidis 3/26/2015 #13

如果在 Android 上,您可以使用以下功能:

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

评论

0赞 林果皞 1/24/2018
请注意,如果字符串未编码(例如包含空格或中文字符),这将不起作用,请参阅:stackoverflow.com/a/14321470/1074998
0赞 Ahmad 6/11/2021
除了英语语言之外,它没有得到扩展
1赞 Alfaville 5/24/2015 #14
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
1赞 Rivalion 6/16/2015 #15

在这里,我做了一个小方法(但不是那么安全,并且不检查很多错误),但如果只有你在编写一个通用的 java 程序,这足以找到文件类型。这不适用于复杂的文件类型,但这些文件类型通常不会被大量使用。

    public static String getFileType(String path){
       String fileType = null;
       fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
       return fileType;
}

评论

0赞 Panther 6/25/2015
OP正在寻找内置方法
0赞 Radiodef 8/10/2018
(1)您应该正确使用文件名。(2)没有延期的情况要妥善处理。此方法返回的路径类似于 ,这没有任何意义。返回或 .(3) 文件分隔符并不总是 /lastIndexOfjohn.smith.report.docABC/XYZabc/xyz""null
19赞 yavuzkavus 3/29/2016 #16

这是一种经过测试的方法

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"));
}
4赞 Vikram Bhardwaj 4/24/2016 #17

这个特殊的问题给我带来了很多麻烦,然后我找到了一个非常简单的解决方案来解决这个问题,我在这里发布。

file.getName().toLowerCase().endsWith(".txt");

就是这样。

评论

4赞 Predrag Manojlovic 6/29/2016
OP 需要一种方法来提取扩展 - 而不是测试一个。
0赞 Vikram Bhardwaj 7/2/2016
实际上,无论您正在开发什么,在大多数情况下,您只需要处理特定类型的文件。因此,如果您的问题出现在这个领域,这将对您有所帮助。
6赞 Predrag Manojlovic 7/2/2016
这并不能满足他的要求
3赞 Ediolot 2/26/2017
这不是问题的答案,但这确实是我一直在寻找的。
1赞 Vasanth 11/18/2016 #18

从文件名获取文件扩展名

/**
 * The extension separator character.
 */
private static final char EXTENSION_SEPARATOR = '.';

/**
 * The Unix separator character.
 */
private static final char UNIX_SEPARATOR = '/';

/**
 * The Windows separator character.
 */
private static final char WINDOWS_SEPARATOR = '\\';

/**
 * The system separator character.
 */
private static final char SYSTEM_SEPARATOR = File.separatorChar;

/**
 * Gets the extension of a filename.
 * <p>
 * This method returns the textual part of the filename after the last dot.
 * There must be no directory separator after the dot.
 * <pre>
 * foo.txt      --> "txt"
 * a/b/c.jpg    --> "jpg"
 * a/b.txt/c    --> ""
 * a/b/c        --> ""
 * </pre>
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename the filename to retrieve the extension of.
 * @return the extension of the file or an empty string if none exists.
 */
public static String getExtension(String filename) {
    if (filename == null) {
        return null;
    }
    int index = indexOfExtension(filename);
    if (index == -1) {
        return "";
    } else {
        return filename.substring(index + 1);
    }
}

/**
 * Returns the index of the last extension separator character, which is a dot.
 * <p>
 * This method also checks that there is no directory separator after the last dot.
 * To do this it uses {@link #indexOfLastSeparator(String)} which will
 * handle a file in either Unix or Windows format.
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there
 * is no such character
 */
public static int indexOfExtension(String filename) {
    if (filename == null) {
        return -1;
    }
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
    int lastSeparator = indexOfLastSeparator(filename);
    return (lastSeparator > extensionPos ? -1 : extensionPos);
}

/**
 * Returns the index of the last directory separator character.
 * <p>
 * This method will handle a file in either Unix or Windows format.
 * The position of the last forward or backslash is returned.
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there
 * is no such character
 */
public static int indexOfLastSeparator(String filename) {
    if (filename == null) {
        return -1;
    }
    int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
    int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
    return Math.max(lastUnixPos, lastWindowsPos);
}

学分

  1. 从 Apache FileNameUtils 类复制 - http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/1.3.2/org/apache/commons/io/FilenameUtils.java#FilenameUtils.getExtension%28java.lang.String%29
3赞 Dmytro Sokolyuk 1/30/2017 #19

REGEX版本怎么样:

static final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");

Matcher m = PATTERN.matcher(path);
if (m.find()) {
    System.out.println("File path/name: " + m.group(1));
    System.out.println("Extention: " + m.group(2));
}

或支持 null 扩展名:

static final Pattern PATTERN =
    Pattern.compile("((.*\\" + File.separator + ")?(.*)(\\.(.*)))|(.*\\" + File.separator + ")?(.*)");

class Separated {
    String path, name, ext;
}

Separated parsePath(String path) {
    Separated res = new Separated();
    Matcher m = PATTERN.matcher(path);
    if (m.find()) {
        if (m.group(1) != null) {
            res.path = m.group(2);
            res.name = m.group(3);
            res.ext = m.group(5);
        } else {
            res.path = m.group(6);
            res.name = m.group(7);
        }
    }
    return res;
}


Separated sp = parsePath("/root/docs/readme.txt");
System.out.println("path: " + sp.path);
System.out.println("name: " + sp.name);
System.out.println("Extention: " + sp.ext);

*nix 的结果:路径:/root/docs/
名称:自述扩展
名:

txt

对于 windows,parsePath(“c:\windows\readme.txt”):
path: c:\windows\
name: readme
扩展名: txt

2赞 schuttek 2/18/2017 #20

这是以 Optional 作为返回值的版本(因为您无法确定文件具有扩展名)...还有健全性检查......

import java.io.File;
import java.util.Optional;

public class GetFileExtensionTool {

    public static Optional<String> getFileExtension(File file) {
        if (file == null) {
            throw new NullPointerException("file argument was null");
        }
        if (!file.isFile()) {
            throw new IllegalArgumentException("getFileExtension(File file)"
                    + " called on File object that wasn't an actual file"
                    + " (perhaps a directory or device?). file had path: "
                    + file.getAbsolutePath());
        }
        String fileName = file.getName();
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            return Optional.of(fileName.substring(i + 1));
        } else {
            return Optional.empty();
        }
    }
}
1赞 Farah 6/23/2017 #21

在不使用任何库的情况下,可以使用 String 方法拆分,如下所示:

        String[] splits = fileNames.get(i).split("\\.");

        String extension = "";

        if(splits.length >= 2)
        {
            extension = splits[splits.length-1];
        }
16赞 VelocityPulse 8/24/2017 #22
String path = "/Users/test/test.txt";
String extension = "";

if (path.contains("."))
     extension = path.substring(path.lastIndexOf("."));

返回“.txt”

如果您只想要“txt”,请使path.lastIndexOf(".") + 1

评论

1赞 riddle_me_this 1/15/2023
这是为数不多的答案之一,可以消除对它返回的内容的混淆。
-1赞 Adnane 11/8/2017 #23

试试这个。

String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
10赞 intrepidis 2/15/2018 #24

从所有其他答案中可以明显看出,没有足够的“内置”功能。这是一种安全而简单的方法。

String getFileExtension(File file) {
    if (file == null) {
        return "";
    }
    String name = file.getName();
    int i = name.lastIndexOf('.');
    String ext = i > 0 ? name.substring(i + 1) : "";
    return ext;
}
0赞 DDPWNAGE 12/16/2018 #25

我喜欢 spectre 回答的简单性,在他的一条评论中链接的是指向另一个答案的链接,该答案修复了 EboMike 提出的另一个问题中的点。

在不实现某种第三方 API 的情况下,我建议:

private String getFileExtension(File file) {

    String name = file.getName().substring(Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')) < 0 ? 0 : Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')));
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf + 1); // doesn't return "." with extension
}

例如,在必须传入文件格式的任何 ImageIO 写入方法中,这样的东西可能很有用。

当您可以 DIY 时,为什么要使用整个第三方 API?

10赞 Jens.Huehn_at_SlideFab.com 1/29/2019 #26

这是 Java 8 的另一个单行代码。

String ext = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null)

其工作原理如下:

  1. 使用 “.” 将字符串拆分为字符串数组。
  2. 将数组转换为流
  3. 使用 reduce 获取流的最后一个元素,即文件扩展名
18赞 Yiao SUN 8/26/2020 #27

如果你在项目中使用 Spring 框架,那么你可以使用 StringUtils

import org.springframework.util.StringUtils;

StringUtils.getFilenameExtension("YourFileName")
1赞 user16123931 8/8/2021 #28
    private String getExtension(File file)
        {
            String fileName = file.getName();
            String[] ext = fileName.split("\\.");
            return ext[ext.length -1];
        }
0赞 Nolle 4/3/2022 #29

流利的方式:

public static String fileExtension(String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .filter(i-> i > fileName.lastIndexOf(File.separator))
            .map(fileName::substring).orElse("");
}
9赞 Nikolas Charalambidis 11/4/2022 #30

Java 20 EA

从 Java 20 EA(抢先体验)开始,终于有了一个新的方法 Path#getExtension,它将扩展返回为:String

Paths.get("/Users/admin/notes.txt").getExtension();              // "txt"
Paths.get("/Users/admin/.gitconfig").getExtension();             // "gitconfig"
Paths.get("/Users/admin/configuration.xml.zip").getExtension();  // "zip"
Paths.get("/Users/admin/file").getExtension();                   // null

评论

1赞 MrFlick 1/7/2023
实际上,这似乎已从 20 个增加到 21 个:bugs.openjdk.org/browse/JDK-8298303
0赞 Nikolas Charalambidis 1/15/2023
@MrFlick 有趣...但我不明白为什么他们决定将其从 20 中删除,如果它是无影响的并且已经存在。
0赞 MrFlick 1/16/2023
如果您遵循一些线程,则可以对返回值应该是什么存在分歧。他们花了额外的时间来制定细节,这意味着他们错过了 20 的最后期限。看起来 21 中包含的版本将在扩展名称中包含点。