Ashish Sharma
Ashish Sharma

Reputation: 875

Can we rollback File mkdir in java?

i have a scenario for creating more then one directories(100 or more) with java File mkdir, i am not sure about this, if anything goes wrong, do we have any logic to rollback(delete) all directories which are newly created?

for(User user: users){
  File file = new File("Directory");
  if(!file.exist()){
   file.mkdir();
   // if anything goes wrong
   rollback();
  }
}

i have already searched on google but did find any suitable answer.

Upvotes: 0

Views: 518

Answers (2)

Alex Fitzpatrick
Alex Fitzpatrick

Reputation: 644

There's nothing built into java for this. I suggest you keep a data structure that tracks your changes as you go and if you need to rollback you just have to iterate over it.

Psuedo code:

boolean rollback = false;
List<File> changes = new ArrayList<File>();

for(int i = 0; i < users.length() && !rollback; i++) {
  User user = users.get(i);
  File file = new File("Directory");
  if(!file.exist()){
    try {
      file.mkdir();
      changes.add(file);
    } catch (Throwable t) {
      rollback = true;
  }
}

if (rollback) {
  // report failure?
  try {
    for(File file : changes) {
      file.rmdir();
    }
  } catch (Throwable t) {
      //So something smart here.
  }
}

Upvotes: 2

giorashc
giorashc

Reputation: 13713

There is no api for rollbacking a mkdir operation so just keep a list of the directories which have been created successfully and delete them if something goes wrong

Upvotes: 2

Related Questions