Adding an infix between file name and extension using java 8

Viewed 2033

In my code, I would like to transform a path of the form

/a/path/to/a/file/image.jpg

to

/a/path/to/a/file/image_resized.jpg

Currently, I am using the the following code which uses FilenameUtils from apache commons IO.

public Path resize(Path original) {
    String baseName = FilenameUtils.getBaseName(original.toString());
    String extension = FilenameUtils.getExtension(original.toString());
    return Paths.get(original.getParent().toString(), baseName + "_resized." + extension);
}

I was wondering if some of this code could be enhanced using java 8 features, specifically:

  • is there a java-8 way for extracting the extension and basename, without using a dependency on Apache Commons IO (FilenameUtils), and without regex (I prefer dependency on apache commons IO over using a regex here)
  • joining to Paths without toString() in Paths.get(existingPath.toString(), "path/to/append");

The second part of the question is answered in Combine paths in Java

5 Answers
Related