简体   繁体   中英

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.

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.
  }
}

没有用于回滚mkdir操作的api,因此只需保留已成功创建的目录的列表,并在出现问题时将其删除

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM