java.io.File.plus() 适用于参数类型: (java.lang.String) value: [\] in Ready API

avi*_*der 4 java groovy file ready-api

我有以下 Groovy 脚本,我试图在其中获取目录名和文件名:

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
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,出现以下异常:

“java.io.File.plus() 适用于参数类型”

为什么创建fullpath变量会抛出这个异常?

Szy*_*iak 6

当您使用+运算符时,Groovy 会取表达式的左侧部分并尝试调用表达式右侧部分的方法.plus(parameter)where parameter。这意味着表达

dir + "\\" + fileName
Run Code Online (Sandbox Code Playgroud)

相当于:

(dir.plus("\\")).plus(filename)
Run Code Online (Sandbox Code Playgroud)

dir您的示例中的变量是File,因此编译器会尝试查找如下方法:

File.plus(String str)
Run Code Online (Sandbox Code Playgroud)

并且该方法不存在,您会得到:

Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.plus() is applicable for argument types: (java.lang.String) values: [\]
Run Code Online (Sandbox Code Playgroud)

解决方案

如果您想构建一个字符串,就像String fullpath = dir + "\\" + fileName您必须获得dir变量的字符串表示一样,例如dir.path返回一个表示文件完整路径的字符串:

String fullpath = dir.path + "\\" + fileName
Run Code Online (Sandbox Code Playgroud)