Ensure directories exist

I’m using java.io to create a file. I’d like to ensure that the leading directories exist in order to avoid an error such as

generating target/temperatures/average/2/earth-scatter-month-2015.png
Exception in thread "main" java.io.IOException: No such file or directory
	at java.io.UnixFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:1012)
	at globe.EarthMap.output(EarthMap.scala:157)

Is there something like ensureDirectoriesExist(file) where I can give the name of the file I want to create, or do I really need to parse out the name of the directory myself and check explicitly whether the directory exists, creating if necessary?

  def output(fileName: String):Boolean = {
    if (borders) {
    import javafx.embed.swing.SwingFXUtils._
    import javax.imageio.ImageIO.write
    val file = new java.io.File(fileName)
    println(s"generating $file")
    ///  TODO, I want to ensure the directory exists otherwise file creation will fail
    write(fromFXImage(wimg,null),"png", file)

I’ve discovered I can use file.getParentFile().mkdirs() and that will create the directories leading to the intended file. Perhaps that’s the correct solution?

1 Like

That is the solution that I have used in the past. I’m not certain if it is the ideal solution, but it seems to work well.

1 Like