【问题标题】:Java — Loop create directories by numberJava——按编号循环创建目录
【发布时间】:2023-03-11 16:17:01
【问题描述】:

所以我的问题是我想让我的目录循环如下: https://gyazo.com/74209ec6e199adc3cd84460f7e0d5c2e

我创建目录的代码:

public static File createDir(String path, String name) {
    File dir = new File(path + "\\" + name);
    dir.mkdir();
    return dir;

}

public static void createDirs(String path, int times) {
    int x;
    for(x=1; x < times+1; x++){
        Utils.createDir(path+File.separator, Integer.toString(x));
    }

}

public static void main(String[] args){
    Utils.createDir(System.getProperties().getProperty("user.home")+File.separator+"Desktop", "Dir");
    createDirs(System.getProperties().getProperty("user.home")+File.separator+"Desktop"+File.separator+"Dir", 10);
}

}

但我不知道怎么做。任何帮助表示赞赏。

编辑:现在看起来像这样: https://gyazo.com/e4877b87c6d9e1910bad7849daafd431

【问题讨论】:

    标签: java io directory


    【解决方案1】:

    需要修改createDirs循环内的path变量

    public static void createDirs(String path, int times) {
        int x;
        for(x=1; x < times+1; x++){
            path += File.separator + Integer.toString(x);
            new File(path).mkdir();
        }
    }
    

    【讨论】:

      【解决方案2】:

      @Zain Drozal 这是你想要的修改后的代码

      package stack;
      
      import java.io.File;
      
      public class Utils {
        static File lastDir;
      
        public static File createDir(String path, String name) {
          File dir = new File(path + "\\" + name);
          dir.mkdir();
          return dir;
        }
      
        public static void createDirs(String path, int times) {
          int x;
          for(x=1; x < times+1; x++){
           lastDir = Utils.createDir(lastDir.getPath()+File.separator, Integer.toString(x));
          }
        }
      
        public static void main(String[] args) {
          lastDir = Utils.createDir(System.getProperties().getProperty("user.home")+File.separator+"Desktop", "Dir");
          createDirs(System.getProperties().getProperty("user.home")+File.separator+"Desktop"+File.separator+"Dir", 10);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 2021-01-13
        相关资源
        最近更新 更多