How add file extension to a filename containing dots?


#1

I’ve been using code like

openSong(file.getChildFile(songname).withFileExtension("xml"));

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?


#2

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!


#3

Yeah, you’d be surprised. Or not…


#4

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

Tom


#5

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:


#6

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


#7

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.


#8

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!