Java createNewFile () - will it create directories?

I have a condition to check if a specific file exists before continuing ( ./logs/error.log ). If it is not found, I want to create it. However,

 File tmp = new File("logs/error.log"); tmp.createNewFile(); 

also create logs/ if it does not exist?

+73
java file directory io
Jul 12 '11 at 2:59 p.m.
source share
6 answers

No.
Use tmp.getParentFile().mkdirs() before creating the file.

+169
Jul 12 '11 at 15:00
source share
 File theDir = new File(DirectoryPath); if (!theDir.exists()) theDir.mkdirs(); 
+18
Jul 12 '11 at 15:02
source share
 File directory = new File(tmp.getParentFile().getAbsolutePath()); directory.mkdirs(); 

If directories already exist, nothing will happen, so you don't need checks.

+14
Jul 12 '11 at 15:09
source share

StringUtils.touch(/path/filename.ext) now (> = 1.3) also create a directory and a file if they do not exist.

+3
Apr 09 '15 at 19:56
source share

Java 8 style

 Path path = Paths.get("logs/error.log"); Files.createDirectories(path.getParent()); 

Write to file

 Files.write(path, "Log log".getBytes()); 

To read

 System.out.println(Files.readAllLines(path)); 

Full example

 public class CreateFolderAndWrite { public static void main(String[] args) { try { Path path = Paths.get("logs/error.log"); Files.createDirectories(path.getParent()); Files.write(path, "Log log".getBytes()); System.out.println(Files.readAllLines(path)); } catch (IOException e) { e.printStackTrace(); } } } 
+2
May 31 '18 at 8:40
source share

No, and if logs do not exist, you will get java.io.IOException: No such file or directory

An interesting fact for Android developers: calls to the similar Files.createDirectories() and Paths.get() will work with support for min api 26.

0
Feb 03 '19 at
source share



All Articles