I have following Groovy script where I'm trying to fetch the directory name and the file name:
File dir = new File("C://Users//avidCoder//Project")
log.info dir //Fetching the directory path
String fileName = "Demo_Data" + ".json"
log.info fileName //Fetching the file name
String fullpath = dir + "\\" + fileName
log.info fullpath //Fetching the full path gives error
However when I run it, I get the following exception:
"java.io.File.plus() is applicable for arguments type"
Why does creating fullpath
variable throws this exception?
When you use +
operator, Groovy takes the left side part of the expression and tries to invoke method .plus(parameter)
where parameter
is the right side part of the expression. It means that expression
dir + "\\" + fileName
is an equivalent of:
(dir.plus("\\")).plus(filename)
dir
variable in your example is File
, so compiler tries to find a method like:
File.plus(String str)
and that method does not exist and you get:
Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.plus() is applicable for argument types: (java.lang.String) values: [\]
If you want to build a string like String fullpath = dir + "\\" + fileName
you will have to get a string representation of dir
variable, e.g. dir.path
returns a string that represents file's full path:
String fullpath = dir.path + "\\" + fileName
Because dir
is of type File
and File
has no plus(String)
method.
You probably want
String fullpath = dir.path + "\\" + fileName
And in case you ever want to use it on other Platforms than Windows:
String fullpath = dir.path + File.separator + fileName
You could also have a look at Path.join()
which is explained in an other answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With