Java, automatically change file name if file exists

If you want to save a file to a certain directory, but don’t want to overwrite existing file. You want to append the file name with an index. Say, you want your file as “myFile.txt”. If “myFile.txt” exists already, you want to change your file name to “myFile1.txt”.

Here is the solution.


String fileName = "myFile";
String extension = ".txt";
String fixedPrefix = fileName;
Integer i=1;

boolean oldFileExist = true;
while (oldFileExist)
{
try {
FileInputStream inputStream = new FileInputStream(fileName + extension);
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileName = fixedPrefix + i.toString();
i++;

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
oldFileExist = false;
}
}

fileName = fileName + extenstion; //fileName now should be like myFile1.txt

//now continue to create a file with fileName as name, then write to it as normal

BufferedWriter fileBuff = new BufferedWriter(new FileWriter(fileName , false));
//write your content here
//bla bla
//.....

fileBuff.close()