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()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s