user8887422
user8887422

Reputation:

How do I make a new file everytime so nothing gets overwritten?

I have this code here that saves bitmaps of images as a GIF file called test, but everytime the user saves it as test.gif so its constantly overwriting.

What are some ways to avoid overweriting and generate a new filename everytime programmatically?

if(imagesPathList !=null){
    if(imagesPathList.size()>1) {
        Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
        dir.mkdirs();
        File file = new File(dir, "test.gif");

        try{
            FileOutputStream f = new FileOutputStream(file);
            f.write(generateGIF(list));
        } catch(Exception e) {
            e.printStackTrace();
        }

Upvotes: 0

Views: 141

Answers (2)

Lothar
Lothar

Reputation: 5459

You can use java.io.File.createTempFile("test", ".gif", dir)

This creates unique filename but they might get significantly long after some time.

Alternatively you can create a method that creates unique filesnames yourself:

private File createNewDestFile(File path, String prefix, String suffix) {
    File ret = new File(path, prefix + suffix);
    int counter = 0;
    while (ret.exists()) {
        counter++;
        ret = new File(path, prefix + "_" + counter + suffix);
    }
    return ret;
}

Instead of

File file = new File(dir, "test.gif");

you call

File file = createNewDestFile(dir, "test", ".gif");

This is not thread safe. For that you need a more sophisticated method (e.g. synchronize it and create a FileOutputStream instead of a File which is creating the file already before another call checks of the method checks its existence).

Upvotes: 1

Lukas Bradley
Lukas Bradley

Reputation: 489

A quick and dirty solution is to put the system time in the filename:

File file = new File(dir, "test_" + System.currentTimeMillis() +".gif");

As long as that method isn't executed at the exact same millisecond, you won't have duplicates.

Upvotes: 2

Related Questions