Concatenating to a file name before the ‘.’ Filename extension in Java

In case file name can contain more then one dot like foo.bar.txt you should find index of last dot (String#lastIndexOf(char) can be useful here).

  • To get file name without extension (foo.bar part) substring(int, int) full file name from index 0 till index of that last dot.
  • To get extension (.txt part from last dot till the end of string) substring(int) from last dot index.

So your code can look like:

int lastDotIndex = r.lastIndexOf('.');
String s = r.substring(0, lastDotIndex ) + "V1" + r.substring(lastDotIndex);

Look at String.indexOf() and String.substring() to split the string up and rebuild your updated version.


Another approach is to use Apache Commons IO's FilenameUtils class to get the file's base name and extension.

import org.apache.commons.io.FilenameUtils;

...

File file = ...
String filename = file.getName();
String base = FilenameUtils.removeExtension(filename);
String extension = FilenameUtils.getExtension(filename);
String result = base + "-something-here" + "." + extension;

Tags:

Java