Make a new filename if old file exists

77 views Asked by At

I am trying to check if file exsist. If it does just want to increment the new filename. So this is how I have done:

File gpxfile = new File(root, "Avvikelserapport" + dateofday.getText().toString() + customer.getText().toString() + ".pdf");
    int counter = 0;
    if (gpxfile.exists())
    {
        counter = counter + 1;
        File newfilename = new File(root, "Avvikelserapport" + dateofday.getText().toString() + customer.getText().toString() + counter + ".pdf");
        PdfWriter.getInstance(document, new FileOutputStream(newfilename));
    }
    else
    {
        PdfWriter.getInstance(document, new FileOutputStream(gpxfile));
    }

The problem is that I think I have the counter wrong because it only make a new file once.

ex.

If I have a file with name "File.pdf" and then check if it exists it makes a new name "File1.pdf" but after this it does not make a new file with the name "File2.pdf".

1

There are 1 answers

0
isma3l On

try this:

    int counter=0;
    File gpxfile = new File(root, "Avvikelserapport" + dateofday.getText().toString() + customer.getText().toString() + ".pdf");
    while(gpxfile.exists())
    {
        counter = counter + 1;
        gpxfile = new File(root, "Avvikelserapport" + dateofday.getText().toString() + customer.getText().toString() + counter + ".pdf");

    }
    PdfWriter.getInstance(document, new FileOutputStream(gpxfile));