4

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?

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
avidCoder
  • 440
  • 2
  • 10
  • 28
  • it works properly. At least the code I can understand from your question. You are just adding strings there. – Veselin Davidov Apr 12 '18 at 06:48
  • Actually I am using Ready API tool. There it seems to be some problem – avidCoder Apr 12 '18 at 06:52
  • I am getting this error in Ready API - "groovy.lang.MissingMethodException: No signature of method: java.io.File.plus() is applicable for argument types: (java.lang.String) values: [\] Possible solutions: list(), list(java.io.FilenameFilter), split(groovy.lang.Closure), use([Ljava.lang.Object;), is(java.lang.Object), wait()" – avidCoder Apr 12 '18 at 06:54

2 Answers2

7

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: [\]

Solution

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
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
3

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

Mene
  • 3,739
  • 21
  • 40