diff a/src/java.base/share/classes/java/nio/file/Path.java b/src/java.base/share/classes/java/nio/file/Path.java --- a/src/java.base/share/classes/java/nio/file/Path.java +++ b/src/java.base/share/classes/java/nio/file/Path.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this @@ -246,10 +246,54 @@ * @return a path representing the name of the file or directory, or * {@code null} if this path has zero elements */ Path getFileName(); + /** + * Returns the extension of the file name of this path as a {@code String}, + * where the extension is defined to be the portion of the {@code String} + * representation of the file name after the last dot ('.'). If the first + * character in the file name string is a dot it is ignored. If the + * extension cannot be determined, then the empty string is returned. This + * will occur if the path has zero elements ({@link #getFileName()} returns + * {@code null}), or the file name string has fewer than three characters, + * does not contain a dot, only the first character is a dot, or the last + * character is a dot. + * + * @implSpec + * The default implementation is equivalent for this path to: + *
{@code + * String name = getFileName().toString(); + * int length = name.length(); + * int lastDot = name.lastIndexOf('.'); + * length > 2 && lastDot > 0 && lastDot < length - 1 ? + * name.substring(lastDot + 1) : ""; + * }+ * + * @return the extension of the file name of this path, or the empty + * string if the extension is indeterminate + */ + default String getExtension() { + Path fileName = getFileName(); + if (fileName == null) { + return ""; + } + + String fileNameString = fileName.toString(); + int length = fileNameString.length(); + + // Indeterminate if fileNameString is too short + if (length > 2) { + int lastDotIndex = fileNameString.lastIndexOf('.'); + // Indeterminate if no dot or found at last or only the first index + if (lastDotIndex > 0 && lastDotIndex < length - 1) { + return fileNameString.substring(lastDotIndex + 1); + } + } + return ""; + } + /** * Returns the parent path, or {@code null} if this path does not * have a parent. * *
The parent of this path object consists of this path's root