Check if File Exists in Groovy

Check if File Exists in Groovy

  • Groovy
  • 1 min read

To check if a file exists in Groovy, you can use the new File(<file_name>).exists() method. Here's an example:

def fileName = "myfile.txt"
if (new File(fileName).exists()) {
  println "$fileName exists"
} else {
  println "$fileName does not exist"
}

This code checks if a file named myfile.txt exists in the current directory. If it does, it prints "myfile.txt exists". If it does not, it prints "myfile.txt does not exist".

Here's another example that shows how to check if a file exists in a specific directory:

def fileName = "myfile.txt"
def dir = "/path/to/dir"
if (new File(dir, fileName).exists()) {
  println "$fileName exists in $dir"
} else {
  println "$fileName does not exist in $dir"
}

In this code, we check if the file myfile.txt exists in the directory /path/to/dir. If it does, it prints "myfile.txt exists in /path/to/dir". If it does not, it prints "myfile.txt does not exist in /path/to/dir".

Related:

  1. Check if String is Empty in Groovy
  2. Check if Variable is Null in Groovy