Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.File.plus() is applicable for arguments types: (java.lang.String) value: [\] in Ready API

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?

like image 236
avidCoder Avatar asked Jan 28 '23 07:01

avidCoder


2 Answers

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
like image 59
Szymon Stepniak Avatar answered Feb 05 '23 16:02

Szymon Stepniak


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

like image 28
Mene Avatar answered Feb 05 '23 14:02

Mene