LKB
LKB

Reputation: 1040

Android/Java - When a file exists, rename the file

I can't seem to get my logic right, I'm trying to rename a file to "photo2.jpg" if, say "photo.jpg" and "photo1.jpg" exists, and so on.

At the moment when I run my code, and I take a picture, only "photo.jpg" and "photo1.jpg" ever exist, and then they get written over if a third and fourth, etc. photo is taken.

String photoName = "photo.jpg";
        String i = "0";
        int num = 0;

        File photo = new File(Environment.getExternalStorageDirectory(), photoName);

        //for (File file : photo.listFiles()){
        while(photo.exists()) {             
            //if(file.getName().equals("photo.jpg")){
                //photo.delete();
                num = Integer.parseInt(i);
                ++num;
                String concatenatedNum = Integer.toString(num);

                StringBuffer insertNum = new StringBuffer(photoName);
                insertNum.insert(5, concatenatedNum);

                photoName = insertNum.toString();

                photo.renameTo(new File(Environment.getExternalStorageDirectory(), photoName));
            //}
        }


        try {
            FileOutputStream fos=new FileOutputStream(photo.getPath());

            //MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle, yourDescription);

            //write jpeg to local drive
            fos.write(jpeg[0]);
            fos.close();
        }
        catch (java.io.IOException e) {}

Thanks for your time and help!


EDIT: Half solved: I realized I was overwriting the file instead of creating a NEW file. Now I can take multiple pictures and they are saved as their own file. However, the naming of the files is now:

Upvotes: 1

Views: 5847

Answers (3)

BG_NE
BG_NE

Reputation: 123

I know this is older, but I ended up here when I was looking for a solution. I ended up doing the following:

String baseFilename = "photo";
File outputFile = new File(Environment.getExternalStorageDirectory(), baseFilename + ".jpg");
int i = 2; // whatever increment you want to start with, I'm copying Windows' naming convention
while (outputFile.exists()){
    outputFile = new File(Environment.getExternalStorageDirectory(), baseFilename + "(" + i + ")" + ".jpg");
    i++;
}

You will end up with photo.jpg, photo(2).jpg, photo(3).jpg, etc.

Obviously you can easily change how the int is appended, but like I said I just decided to follow how Windows does it.

Upvotes: 1

mrres1
mrres1

Reputation: 1155

private void savePhoto(String fileName, final String extension)
{
    // First, get all the file names from the directory
    String[] allFiles = new File(Environment.getExternalStorageDirectory().toString()).list();

    // Create a new empty list to put all the matching file names in
    //  In this case all the files names that are "photo.jpg" or "photo#.jpg"
    ArrayList<String> files = new ArrayList<String>();

    // Skim through all the files
    for(String file : allFiles)
    {
        // Use a regular expression to find matching files
        //  fileName[0-9]+\.extension|fileName\.extension
        if(file.matches(fileName + "[0-9]+\\." + extension + "|" + fileName + "\\." + extension))
        {
            files.add(file);
        }
    }

    files.trimToSize();

    // Now sift through the list and find out what the highest number is
    //  Example, if you've taken 8 photos, then highestNumber will equal 8
    int highestNumber = 0;
    int digit;

    for(String file : files)
    {
        try
        {
            digit = Integer.parseInt(file.replace(fileName, "").replace("." + extension, ""));
        }
        catch(NumberFormatException e)
        {
            digit = 1;
        }

        if(digit > highestNumber)
        {
            highestNumber = digit;
        }
    }

    // Create the file object
    fileName = fileName + highestNumber++ + "." + extension;
    File file = new File(Environment.getExternalStorageDirectory().toString(), fileName);


    // In not sure what you do around here, I can't find any array titled "jpeg"
    //  So do what you will
    FileOutputStream fostream = null;

    try
    {
        fostream = new FileOutputStream(file);

        //MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle, yourDescription);

        //write jpeg to local drive
        fostream.write(jpeg[0]);

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(fostream != null)
        {
            try
            {
                fostream.flush();
                fostream.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

Upvotes: 0

John3136
John3136

Reputation: 29266

You always base your filename on i, but you never change the value of i when you find that number is used.

Upvotes: 1

Related Questions