How to create a directory and sub directory structure with java?

后端 未结 5 1430
忘了有多久
忘了有多久 2020-12-29 05:39

Hello there I want to create the directories and sub directories with the java. My directory structure is starts from the current application directory, Means in current pro

5条回答
  •  醉话见心
    2020-12-29 06:19

    Starting from Java 7, you can use the java.nio.file.Files & java.nio.file.Paths classes.

    Path path = Paths.get("C:\\Images\\Background\\..\\Foreground\\Necklace\\..\\Earrings\\..\\Etc");
    
    try {
        Files.createDirectories(path);
    } catch (IOException e) {
        System.err.println("Cannot create directories - " + e);
    }
    

    This is a tricky solution (because I used only one path to go to the whole structure).

    If you don't like tricky solutions, you can use 4 simple paths instead:

    Path p1 = Paths.get("C:\\Images\\Background");
    Path p2 = Paths.get("C:\\Images\\Foreground\\Necklace");
    Path p3 = Paths.get("C:\\Images\\Foreground\\Earrings");
    Path p4 = Paths.get("C:\\Images\\Foreground\\Etc");
    

    and then call the createDirectories method for all of them:

    Files.createDirectories(p1);
    Files.createDirectories(p2);
    Files.createDirectories(p3);
    Files.createDirectories(p4);
    

提交回复
热议问题