RFR: 8057113: (fs) Path should have a method to obtain the filename extension [v4]

Roger Riggs rriggs at openjdk.java.net
Wed Apr 27 18:29:51 UTC 2022


On Thu, 21 Apr 2022 23:13:19 GMT, Brian Burkhalter <bpb at openjdk.org> wrote:

>> Resurrection of the proposal to add a method to obtain the filename extension originated in PR [2319](https://github.com/openjdk/jdk/pull/2319).
>
> Brian Burkhalter has updated the pull request incrementally with one additional commit since the last revision:
> 
>   8057113: Implement reviewer suggestions for replaceExtension()

src/java.base/share/classes/java/nio/file/Path.java line 262:

> 260:      * the path has zero elements ({@link #getFileName()} returns
> 261:      * {@code null}), or the file name string does not contain a dot, only
> 262:      * the first character is a dot, or the last character is a dot.

Musing on a filename with a final dot, i.e.  `FooBar.`
I think it has an empty string "" as the extension (because there is a dot).

As described, if the `defaultExtension` is returned, then it would be nice for the code to trust
that there is no final dot.  If it is case when the `defaultExtension` is returned, there may or may not be a final dot then the caller may need to test separately for it before using the filename.

src/java.base/share/classes/java/nio/file/Path.java line 278:

> 276:      *
> 277:      * @return  the file name extension of this path, or
> 278:      *          {@code defaultExtension} if the extension is indeterminate

Seeing the use of `Optional<String> below`, returning an `Optional<String>` for this method might also be a good idea. (And dropping the `defaultExtension` parameter).
The testing for a missing extension is more obvious and the substitution for a missing extension can be handled by `Optional.orElse(`).

src/java.base/share/classes/java/nio/file/Path.java line 356:

> 354:      *         but is not otherwise checked for validity
> 355:      *
> 356:      * @return a new path equal to this path but with extension replaced by

Drop the word "new"; so it can return the existing Path if there is no change.

src/java.base/share/classes/java/nio/file/Path.java line 370:

> 368:         if (!extension.isEmpty()) {
> 369:             if (extension.indexOf('.') == 0 ||
> 370:                 extension.lastIndexOf('.') == extension.length() - 1)

No need to scan the string using `indexOf`:

`(extension.charAt(0) == '.' || extension.charAt(extension.length()-1) == '.')`

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

PR: https://git.openjdk.java.net/jdk/pull/8066


More information about the nio-dev mailing list