java files createdirectories if they don't exist

http‮w//:s‬ww.lautturi.com
java files createdirectories if they don't exist

To create a directory in Java if it doesn't already exist, you can use the Files.createDirectories() method from the java.nio.file package. Here's an example of how to use it:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    String directory = "./new/directory/path";
    Path path = Paths.get(directory);
    try {
      Files.createDirectories(path);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This code creates a Path object representing the desired directory, and then uses the createDirectories() method to create the directory and all of its parent directories, if they don't already exist.

Note that the createDirectories() method can throw an IOException if there is an error creating the directories. It's a good idea to handle this exception or declare it in the throws clause of your method.

Created Time:2017-11-03 15:57:13  Author:lautturi