Samarland
Samarland

Reputation: 581

Compare files list to object List to delete files

I have a list of plans, each plan has a PDF in ("/web/managed/") I wasn't deleting the files when I delete the plan, so now I'm trying to add a function to delete all files that are not have the ids in my plan list.

Files name always has the id. Example: 6365_Test-LVLD.pdf

list of the object:

@Transaction
public List<StorePlan> getPlans() {
     List<StorePlan> list = getCurrentSession().createCriteria(StorePlan.class).list();
     return list;
}

then I'll get all the files from my folder:

protected File[] getPDFs() {
    return new File("/web/managed/").listFiles();
}

here's my purge function:

protected void getPlanIds() {
    int count = 0;
    for(StorePlan plan : storePlanDao.getPlans()) {
        for (File file : getPDFs()) {
            String  planFileId = file.getName().substring(0, 4);

            if(plan.getId() != Integer.valueOf(planFileId)) {
                file.delete();
                count++;
            }
        }
    }   
}

with my code: it will delete everything from my folder. when I want to keep the files that will still have ids in the other list.

Upvotes: 0

Views: 44

Answers (2)

Neytorokx
Neytorokx

Reputation: 7

I think I see the problem. Instead of deleting the problem within the second loop have it set a Boolean to true and break out of the loop. Outside of the second loop have an if statement that, if true, deletes the file. So:

protected void getPlanIds() {
int count = 0;
for(StorePlan plan : storePlanDao.getPlans()) {
    Boolean found = false;
    for (File file : getPDFs()) {
        String  planFileId = file.getName().substring(0, 4);

        if(plan.getId() == Integer.valueOf(planFileId)) {
            found = true;
            break;
        } else {
           count++;
        }
    }
    if (!found) {
        file.delete();
    }
}   
}

I apologize for bad formatting. I'm on mobile and passing time at work. xD

Upvotes: 1

isaace
isaace

Reputation: 3429

If I understood your question then this should work:

    List<Integer> planIds = Lists.newArrayList();   

    for(StorePlan plan : storePlanDao.getPlans()){
        planIds.add(plan.getId());
    }

    for (File file : getPDFs()) {
        Integer planFileId = Integer.valueOf(file.getName().substring(0, 4))
        if(!ids.contains(planFileId)) {
            file.delete();
            count++;
        }
    }

Upvotes: 1

Related Questions