How add file extension to a filename containing dots?


I’ve been using code like


to create valid file names, where songname is a user supplied string like “masterpiece” or “hell no”. This works fine if songname doesn’t contain a dot “.”, in which case the rest of the string is considered being an extension and skipped, thus giving problems with followups like “hell no. 2”. I find no function like “addExtension” that just adds an extension without parsing the filename after any existing one, so I guess I’ll have to roll my own?


If it’s a user-supplied string you should probably run it through File::createLegalFileName() before using it, as it could contain more surprises than just a dot!


Yeah, you’d be surprised. Or not…


Hey, can’t you use something like upToLasrOccurenceOf with some conditional logic for this?



I’ll just add “.xml” to the songname and do the simple sanity check as suggested by Jules. Until someone yells “you cannot do that, it wont work for [name of your favourite OS]” :slight_smile:


Personally, I’d call createLegalFileName() on it, then remove any dots (or replace them with ‘_’ or something) and then use then normal withFileExtension method.


I settled with a solution where after sanitising the name with createLegalFileName() I replaced any occurence of dots with one of the “unsane” characters (@), which I now knew wouldn’t be in the name, and then after adding the extension, I rereplaced any @ with a dot.


TBH I suggested removing the dots because it’s probably not a great idea to create a filename that contains more than one dot. But whatever works for you!