RFR: 8298318: (fs) APIs for handling filename extensions

Roger Riggs rriggs at openjdk.org
Thu Nov 2 17:34:02 UTC 2023


On Tue, 17 Oct 2023 19:52:14 GMT, Brian Burkhalter <bpb at openjdk.org> wrote:

> Add to `java.nio.file.Path` a method `getExtension` to retrieve the `Path`'s extension, and companion methods `removeExtension` and `addExtension`.

As suggested, I would rename `removeExtension` to `withoutExtension` and replace `addExtension` with `withExtension`.
Please rephrase or reword as you see fit:

    /**
     * Returns a Path with the {@code extension}, replacing the existing extension, if any.
     * If the extension is non-null and non-empty, the "." and the extension
     * is appended to the path returned by {@link #withoutExtension()},
     * otherwise the path returned by {@link #withoutExtension()} is returned.
     *
     * @implSpec
     * The default implementation is equivalent for this path to:
     *
     * {@snippet lang="java" :
     * Path p = withoutExtension();
     * if (extension == null || extension.isEmpty()) {
     *     return p;
     * } else {
     *     return p.resolveSibling(p.getFileName() + "." + extension);
     * }
     *}
     * @param extension
     *        the extension to add, may be {@code null}
     *
     * @return a Path with the {@code extension}, replacing the existing extension, if any
     * 
     * @see #getExtension
     * @see #withoutExtension
     *
     * @since 22
     */
    default Path withExtension(String extension) {
        Path path = withoutExtension();
        if (extension == null || extension.isEmpty())
            return path;

        return path.resolveSibling(path.getFileName() + "." + extension);
    }


Likely there is a more efficient implementation that does not create unnecessary Path intermediate objects.

This is the same as suggested : https://github.com/openjdk/jdk/pull/16226#issuecomment-1768659315

-------------

PR Comment: https://git.openjdk.org/jdk/pull/16226#issuecomment-1791210875
PR Comment: https://git.openjdk.org/jdk/pull/16226#issuecomment-1791216671


More information about the nio-dev mailing list