Stanley Mungai
Stanley Mungai

Reputation: 4150

Create files with same name without overwriting java

I have seen this question before, But I have not been able to come up with a solution from the suggestions. I need to be able to create a file with the same name without overwriting the old one. Say for example if I have images.txt, If I try to create another file with the same name it should be images(1).txt, images(2).txt and so on. So far I am able to create only first index. Here is My code:

public class Filenames {

    public static void main(String[] args) throws IOException {
        String filename = "images.txt";
        File f = new File(getNewFileName(filename));
        f.createNewFile();

    }

    public static String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf("."));
    }

    public static String getNewFileName(String filename) throws IOException {
        File aFile = new File(filename);
        int fileNo = 0;
        String newFileName = "";
        if (aFile.exists() && !aFile.isDirectory()) {
            fileNo++;
            newFileName = filename.replaceAll(getFileExtension(filename), "(" + fileNo + ")" + getFileExtension(filename));
        } else if (!aFile.exists()) {
            aFile.createNewFile();
            newFileName = filename;
        }
        return newFileName;
    }
}

What am I Missing?

Upvotes: 2

Views: 4657

Answers (1)

Arthur
Arthur

Reputation: 98

try this please verify

public static String getNewFileName(String filename) throws IOException {
    File aFile = new File(filename);
    int fileNo = 0;
    String newFileName = "";
    if (aFile.exists() && !aFile.isDirectory()) {


        //newFileName = filename.replaceAll(getFileExtension(filename), "(" + fileNo + ")" + getFileExtension(filename));

        while(aFile.exists()){
            fileNo++;
            aFile = new File("images(" + fileNo + ").txt");
            newFileName = "images(" + fileNo + ").txt";
        }


    } else if (!aFile.exists()) {
        aFile.createNewFile();
        newFileName = filename;
    }
    return newFileName;
}

Upvotes: 6

Related Questions