Jairo Bustos
Jairo Bustos

Reputation: 31

Renaming file if exists in Android

I have been looking at the forum and found some tips but none of them bring me to the final solution. I need the code if possible, please.

I am creating a txt file every time I close my app and what I am aiming for is to rename the file in case it already exists with the following format:

file.txt - file(1).txt - file(2).txt

Up until now what I get is the following:

file.txt - file.txt1 - file.txt12

The code that I have is the following:

int num = 0;
    public void createFile(String name) {  
    try {
        String filename = name;
        File myFile = new File(Environment.getExternalStorageDirectory(), filename);
        if (!myFile.exists()) {
            myFile.createNewFile();
        } else {
            num++;
            createFile(filename + (num));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Thanks everybody in advance!

Upvotes: 0

Views: 1464

Answers (1)

G.T.
G.T.

Reputation: 1557

Your filename variable contains the whole name of your file (i.e. file.txt). So when you do this:

createFile(filename + (num));

It simply adds the number at the end of the file name.

You should do something like this:

int num = 0;

public void createFile(String prefix) {
    try {
        String filename = prefix + "(" + num + ").txt";  //create the correct filename
        File myFile = new File(Environment.getExternalStorageDirectory(), filename);

        if (!myFile.exists()) {
            myFile.createNewFile();
        } else {
            num++;               //increase the file index
            createFile(prefix);  //simply call this method again with the same prefix
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then just call it like this:

createFile("file");

Upvotes: 2

Related Questions