Java 的 createNewFile()-它也会创建目录吗?

在继续之前,我有一个条件来检查某个文件是否存在(./logs/error.log)。如果没有找到,我想创建它。但是,威尔

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

也创建 logs/,如果它不存在?

96746 次浏览

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

File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();

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

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

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();
}
}
}

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.