Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an infix between file name and extension using java 8

Tags:

java

path

java-8

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

like image 989
Stijn Haezebrouck Avatar asked Dec 24 '22 15:12

Stijn Haezebrouck


1 Answers

You don't need a library for such a small and simple task IMO (and no java-8 does not add support for that); and I also can't tell why a regex is out of the question

    int where = input.lastIndexOf(".");

    String result = input.substring(0, where) + "_resized" + input.substring(where);
    System.out.println(result);
like image 199
Eugene Avatar answered Dec 26 '22 16:12

Eugene