4

我有以下 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() 适用于参数类型”

为什么创建fullpath变量会引发此异常?

4

2 回答 2

6

当您使用+运算符时,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返回一个表示文件完整路径的字符串:

String fullpath = dir.path + "\\" + fileName
于 2018-04-12T06:55:12.263 回答
2

因为dir是类型FileFile没有plus(String)方法。

你可能想要

String fullpath = dir.path + "\\" + fileName

如果您想在 Windows 以外的其他平台上使用它:

String fullpath = dir.path + File.separator + fileName

您还可以查看其他答案Path.join()中解释的内容

于 2018-04-12T06:56:24.203 回答