Java autogenerate directories if exists

前端 未结 2 437
[愿得一人]
[愿得一人] 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...
    }
    
    0 讨论(0)
  • 2021-01-28 09:25
    String folderPrefix = "folder";
    int folderSuffix = 0;
    File fa = new File(folderPrefix + folderSuffix);
    
    while (fa.exists()) {
      fa = new File(folderPrefix + folderSuffix++);
    }
    
    0 讨论(0)
提交回复
热议问题