java.io.File.plus() 适用于参数类型:(java.lang.String) 值:[\] in Ready API
java.io.File.plus() is applicable for arguments types: (java.lang.String) value: [\] in 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
但是当我 运行 它时,我得到以下异常:
"java.io.File.plus() is applicable for arguments type"
为什么创建 fullpath
变量会抛出这个异常?
当您使用 +
运算符时,Groovy 获取表达式的左侧部分并尝试调用方法 .plus(parameter)
,其中 parameter
是表达式的右侧部分表达方式。这意味着表达式
dir + "\" + fileName
相当于:
(dir.plus("\")).plus(filename)
dir
变量在您的示例中是 File
,因此编译器会尝试找到如下方法:
File.plus(String str)
并且该方法不存在,您得到:
Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.plus() is applicable for argument types: (java.lang.String) values: [\]
解决方案
如果你想构建一个像 String fullpath = dir + "\" + fileName
这样的字符串,你必须得到 dir
变量的字符串表示,例如dir.path
returns 表示文件完整路径的字符串:
String fullpath = dir.path + "\" + fileName
因为dir
是File
类型,而File
没有plus(String)
方法。
你可能想要
String fullpath = dir.path + "\" + fileName
如果您想在 Windows 以外的其他平台上使用它:
String fullpath = dir.path + File.separator + fileName
您还可以查看 Path.join()
,在 an other answer
中有解释
我有以下 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
但是当我 运行 它时,我得到以下异常:
"java.io.File.plus() is applicable for arguments type"
为什么创建 fullpath
变量会抛出这个异常?
当您使用 +
运算符时,Groovy 获取表达式的左侧部分并尝试调用方法 .plus(parameter)
,其中 parameter
是表达式的右侧部分表达方式。这意味着表达式
dir + "\" + fileName
相当于:
(dir.plus("\")).plus(filename)
dir
变量在您的示例中是 File
,因此编译器会尝试找到如下方法:
File.plus(String str)
并且该方法不存在,您得到:
Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.plus() is applicable for argument types: (java.lang.String) values: [\]
解决方案
如果你想构建一个像 String fullpath = dir + "\" + fileName
这样的字符串,你必须得到 dir
变量的字符串表示,例如dir.path
returns 表示文件完整路径的字符串:
String fullpath = dir.path + "\" + fileName
因为dir
是File
类型,而File
没有plus(String)
方法。
你可能想要
String fullpath = dir.path + "\" + fileName
如果您想在 Windows 以外的其他平台上使用它:
String fullpath = dir.path + File.separator + fileName
您还可以查看 Path.join()
,在 an other answer