递归创建目录

osl*_*ley 23 java recursion scala file

有没有人知道如何使用Java来创建基于n级深度字母表(az)的子目录?

 /a
    /a
        /a
        /b
        /c
        ..
    /b
        /a
        /b
        ..
    ..
        /a
        /b
        /c
        ..

/b
    /a
        /a
        /b
        ..
    /b
        /a
        /b
        ..
    ..
        /a
        /b
        ..
..
    /a
        /a
        /b
        ..
    /b
        /a
        /b
        ..
    ..
        /a
        /b
        ..
Run Code Online (Sandbox Code Playgroud)

Zhi*_*Zou 121

您可以简单地使用类的mkdirs()方法java.io.File.

例:

new File("C:\\Directory1\\Directory2").mkdirs();
Run Code Online (Sandbox Code Playgroud)

  • 或者自Java 7以来的`Files.createDirectories` (22认同)

小智 12

从 Java 7 开始,首选 java.nio

import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.createDirectories(Paths.get("a/b/c"));
Run Code Online (Sandbox Code Playgroud)


Rex*_*Rex 11

如果您不介意依赖第三方API,Apache Commons IO软件包将直接为您执行此操作.看一下FileUtils.ForceMkdir.

Apache许可证是商业软件开发友好的,即它不要求您按照GPL的方式分发源代码.(这可能是好事也可能是坏事,取决于你的观点).


Joã*_*lva 2

public static void main(String[] args) {
  File root = new File("C:\\SO");
  List<String> alphabet = new ArrayList<String>();
  for (int i = 0; i < 26; i++) {
    alphabet.add(String.valueOf((char)('a' + i)));
  }

  final int depth = 3;
  mkDirs(root, alphabet, depth);
}

public static void mkDirs(File root, List<String> dirs, int depth) {
  if (depth == 0) return;
  for (String s : dirs) {
    File subdir = new File(root, s);
    subdir.mkdir();
    mkDirs(subdir, dirs, depth - 1);
  }
}
Run Code Online (Sandbox Code Playgroud)

mkDirsdepth基于给定的 s 列表递归地创建-level 目录树String,在 的情况下main,该目录树由英文字母表中的字符列表组成。