I want to write a java program that when executed can take a file or a certain format (say .txt) and give as output the same file, but with the extension changed (say .xml).
How do I go about accomplishing this? Thank you.
Joined: Mar 22, 2005
The name of a file -including its extension- can be changed by the java.io.File.renameTo method.
Your example is strange, though - an .xml extension implies that the file is valid XML, which wouldn't be the case for just any old .txt file. (Changing the file extension does not change the file type or file contents.)
My example was hypothetical. I actually have the extension .mm (a FreeMind mindmap file), which is valid XML all the time. So I just want to change the file extension for another program to read and parse the XML contained in the file.
Joined: Jun 04, 2007
split() can be your friend.
SCJP - 86% - June 11, 2009
Joined: May 22, 2006
I will attempt to implement it and get back if I have any problems. Thank you.
K Sathya Narayanan
Joined: Feb 15, 2007
The above program changes the extension of *.txt to *.xml. if ext file is not found , then it creates a file in that name and renames its extension to xml. files with other extension are not renamed or created.
First of all, what if there is no extension? indexOf will return -1, which will cause an IndexOutOfBoundsException. Secondly, what if there are multiple dots in the full filename? lastIndexOf will solve that.
And what if the filename contains the extension twice?