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

java

Solution

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);

Problem

I can’t seem to find a way of concatenating to a file name before the “.” extension in Java and I’m not entirely sure how I would go about this. I have already tried: ``` String s = r + "V1"; ``` Where the variable `r` contains the value of `myFile.txt` and the output is: `myFile.txtV1`, but what I need to achieve is `myFileV1.txt` as I don’t want to overwrite the existing file with the same name but concatenate the `V1` before the `.` filename extension when the file is written. Thanks

Original source