Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 712
Simon Avatar asked Jan 28 '14 21:01

Simon


1 Answers

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);
like image 174
Pshemo Avatar answered Sep 19 '22 06:09

Pshemo