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
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).
foo.bar
part) substring(int, int) full file name from index 0 till index of that last dot..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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With