Java 8+ version:

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

Files.createDirectories(Paths.get("/Your/Path/Here"));

The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.

Answer from Inês Gomes on Stack Overflow
Top answer
1 of 9
339

Java 8+ version:

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

Files.createDirectories(Paths.get("/Your/Path/Here"));

The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.

2 of 9
241

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
    String PATH = "/remote/dir/server/";
    String directoryName = PATH.concat(this.getClassName());
    String fileName = id + getTimeStamp() + ".txt";

    File directory = new File(directoryName);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    File file = new File(directoryName + "/" + fileName);
    try{
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(value);
        bw.close();
    }
    catch (IOException e){
        e.printStackTrace();
        System.exit(-1);
    }
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

🌐
Baeldung
baeldung.com › home › java › java io › create a directory in java
Create a Directory in Java | Baeldung
January 8, 2026 - We’ll achieve this by calling the File::mkdir method on a new File object representing the directory to create: File newDirectory = new File(TEMP_DIRECTORY, "new_directory"); assertFalse(newDirectory.exists()); assertTrue(newDirectory.mkdir()); ...
🌐
IQCode
iqcode.com › code › java › java-create-directory-if-not-exists
java create directory if not exists Code Example
September 8, 2021 - String path = ... File pathAsFile = new File(path); if (!Files.exists(Paths.get(path))) { pathAsFile.mkdir(); } ... Java 2022-03-27 21:50:15 Compilation is not supported for following modules: android.
🌐
Coderanch
coderanch.com › t › 708245 › java › Creating-directory-doesn-exist-writing
Creating a directory if it doesn't exist and then writing a file (I/O and Streams forum at Coderanch)
April 2, 2019 - If you create a File object for the directory you want to create you can use the isDirectory() and exists() methods to determine if a directory (or file) with that name already exists and if it doesn't use the mkDir() or mkDirs() method to create the directory.
🌐
Java67
java67.com › 2014 › 02 › how-to-create-file-and-directory-in-java.html
How to Create File and Directory in Java with Example | Java67
There is another method called mkdirs(), which you can use if parent directory doesn't exist, it's like mkdir -p option from UNIX mkdir command. In this Java program, we will learn how to create file and directory, only if they don't exist already.
🌐
W3Docs
w3docs.com › java
Create a directory if it does not exist and then create the files in that directory as well
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws Exception { String dirName = "mydir"; Path dirPath = Paths.get(dirName); if (!Files.exists(dirPath)) { Files.createDirectory(dirPath); } String fileName = "myfile.txt"; Path filePath = dirPath.resolve(fileName); if (!Files.exists(filePath)) { Files.createFile(filePath); } } }
🌐
CodeSpeedy
codespeedy.com › home › create a directory if it does not exist in java
Create a directory if it does not exist in Java - CodeSpeedy
October 7, 2022 - If the directory exists, the If statement will do nothing and if the directory does not exist it will create the directory.
🌐
ZetCode
zetcode.com › java › createdirectory
Java create directory - learn how to create a directory in Java
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.Set; public class JavaCreateDirectoryWithPermissions { public static void main(String[] args) throws IOException { String fileName = "/home/janbodnar/tmp/newdir"; Path mypath = Paths.get(fileName); if (!Files.exists(mypath)) { Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › how to create directory in java
How to create directory in Java - Mkyong.com
July 29, 2020 - File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2"); if (<b>!</b>files.exists()) { if (files.mkdirs()) { ... Thanks for your feedback. We updated the article, the feedback is irrelevant now.
🌐
Casaflora
casaflora.ca › Trending › java-create-directory-if-not-exists
java create directory if not exists
December 18, 2024 - This older method, available since Java 1.0, works well for simpler scenarios. File.mkdirs() creates the directory and all necessary parent directories.
🌐
Bmnj
bmnj.ca › contentai › java-create-directory-if-not-exists
java create directory if not exists
December 13, 2024 - This article will explore several methods to create a directory in Java only if it doesn't already exist, ensuring your application remains resilient and efficient.
🌐
How to do in Java
howtodoinjava.com › home › i/o › creating new directories in java
Creating New Directories in Java
April 21, 2022 - In runtime, it is possible that ... to create the archive directory in such a way: ... The createDirectory() creates the new directory if all the parent directories exist....
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › dirs.html
Creating and Reading Directories (The Java™ Tutorials > Essential Java Classes > Basic I/O)
You can create a temporary directory using one of createTempDirectory methods: createTempDirectory(Path, String, FileAttribute<?>...) ... The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-file ...
🌐
Delft Stack
delftstack.com › home › howto › java › create directory java
How to Create Directory in Java | Delft Stack
February 2, 2024 - The createDirectories() method does not throw an exception if the directory already exists. ... import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaCreateDirectories ...
🌐
Java Development Journal
javadevjournal.com › home › how to create directory in java
How to create directory in Java | Java Development Journal
June 14, 2017 - It will throw FileAlreadyExist... operation · For creating all nonexistent parent directories first, createDirectories method should be used · public class CreateDirectories { public static void main(String[] args) ...