我已经使用 Groovy 几年了,但不是最近几个月,所以这可能只是一个新手问题。我正在尝试解析日志文件,但是当我尝试这样做时:
myFile.eachLine { line ->
/* 2014 Jul 30 08:55:42:645 GMT -4 BW.TMSJobService-TMSJobService-1
* User [BW-User] - Job-2584 [Process/Common/LogAuditInfo.process/WriteToLog]: */
/* 1234567890123456789012345678901 */
/* 0 1 2 3 */
LogItem logItem = new LogItem()
// get the time stamp
String timestamp = line.substring(0, 31)
SimpleDateFormat sdf = new SimpleDateFormat('yyyy MMM dd HH:mm:ss:S')
logItem.date = sdf.parse(timestamp)
}
我得到这个异常(exception):
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: java.text.SimpleDateFormat.parse() is applicable for argument types: (java.lang.String, ce.readscript.TmsLogReader$_read_closure1_closure3) values: [2014 Jul 30 08:34:47:079 GMT -4, ce.readscript.TmsLogReader$_read_closure1_closure3@14235ed5] Possible solutions: parse(java.lang.String), parse(java.lang.String, java.text.ParsePosition), parse(java.lang.String, java.text.ParsePosition), wait(), clone(), clone() at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55) at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
它始终是闭包中的最后一行。如果我在“解析”之后添加代码,那么它会轰炸这个代码。即使是 "079".toLong() 调用也会出错。
我在堆栈溢出中看到了一些类似的错误,但没有解决我的问题。
最佳答案
它正在尝试调用 SimpleDateFormat::parse(String, Closure)
这是不存在的。某处似乎有错别字。它在 groovy 2.1.8 和 2.3.4 下运行良好。您可以尝试使其更加常规,以检查它是否有一些不在您的示例中的输入错误:
new File("log.log").eachLine { line ->
def item = new LogItem()
def timestamp = line[0..30]
item.date = Date.parse('yyyy MMM dd HH:mm:ss:S', timestamp)
}
关于Groovy:调用 Java API 时缺少方法异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25139498/