Java autogenerate directories if exists

前端 未结 2 438
[愿得一人]
[愿得一人] 2021-01-28 08:38

I\'m trying to check if a directory exists, if that happens I want to give it another number, for example, if \"folderX\" exists I want to create a new one called \"FolderX1\",

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-28 09:21

    Basically, you need some kind of loop that can determine if the incrementing folder still exists...

    File makeMe = new File(folder);
    int index = 0;
    String master = folder;
    while (makeMe.exists()) {
        folder = master + (++index);
        makeMe = new File(folder);
    }
    

    If you're worried about creating an infinite loop, you could place a maximum range...

    int maxRange = 100;
    
    File makeMe = new File(folder);
    int index = 0;
    String master = folder;
    while (makeMe.exists() && index < maxRange) {
        makeMe = new File(master + (++index));
    }
    
    if (index > maxRange) { // || makeMe.exists()
        throw new IOException("Could not find free directory");
    } else {
        // All happy unicorns...
    }
    

提交回复
热议问题