How to check if a directory containing a file exist?

Groovy

Groovy Problem Overview


I am using groovy to create a file like "../A/B/file.txt". To do this, I have created a service and pass the file path to be created as an argument. This service is then used by a Job. The Job will do the logic in creating the file in the specified directory. I have manually created the "A" directory.

How will I create the "B" directory and the file.txt inside the "A" directory through codes to create it automatically?

I need also to check if directories "B" and "A" exists before creating the file.

Groovy Solutions


Solution 1 - Groovy

To check if a folder exists or not, you can simply use the exists() method:

// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )

// If it doesn't exist
if( !folder.exists() ) {
  // Create all folders up-to and including B
  folder.mkdirs()
}

// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
  w << "Some text\n"
}

Solution 2 - Groovy

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchemilleX3View Question on Stackoverflow
Solution 1 - Groovytim_yatesView Answer on Stackoverflow
Solution 2 - GroovyJackView Answer on Stackoverflow