To check if a directory exists in Groovy, you can use the File
class and its exists()
method, like this:
Check if Directory Exists in Groovy Examples
File dir = new File('/path/to/dir') if (dir.exists()) { // do something println('Directory exists') }
In this example, the File
object is created with the path to the directory you want to check. The exists()
method is then called on the File
object, and the result is used in an if
statement to check if the directory exists. If the directory exists, the code inside the if
block will be executed.
Here is another example that shows how to check if a directory exists and create it if it doesn't:
File dir = new File('/path/to/dir') if (!dir.exists()) { dir.mkdirs() }
In this example, the File
object is created with the path to the directory you want to check. The exists()
method is then called on the File
object and negated with the !
operator. If the directory does not exist, the mkdirs()
method is called on the File
object to create the directory and any necessary parent directories.