96

I've got a conditional to check if a certain file exists before proceeding (./logs/error.log). If it isn't found I want to create it. However, will

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

also create logs/ if it doesn't exist?

6 Answers6

208

No.
Use tmp.getParentFile().mkdirs() before you create the file.

Michael Schmidt
  • 9,090
  • 13
  • 56
  • 80
jtahlborn
  • 52,909
  • 5
  • 76
  • 118
22
File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 7
    I propose to use "mkdirs" instead of "mkdir" so your code can also create non-existing parent folders :) – Nimpo Aug 03 '16 at 15:05
14
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();

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

ajon
  • 7,868
  • 11
  • 48
  • 86
Jake Roussel
  • 631
  • 1
  • 6
  • 17
10

Java 8 Style

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

To write on 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();
        }
    }
}
ahmet
  • 1,085
  • 2
  • 16
  • 32
4

StringUtils.touch(/path/filename.ext) will now (>=1.3) also create the directory and file if they don't exist.

NathanChristie
  • 2,374
  • 21
  • 20
0

No, and if logs does not exist you'll receive java.io.IOException: No such file or directory

Fun fact for android devs: calls the likes of Files.createDirectories() and Paths.get() would work when supporting min api 26.

Alejandra
  • 576
  • 6
  • 10