当尝试在Groovy上按换行符进行拆分时,出现错误。

12

我正在尝试使用换行符分割消息并使用以下脚本:

    def mesType = "";
def lines = message.getPayload().split("\n");

if ( lines[0][0..6] == '123456' ||  lines[1][0..6] == '123456') {
    mesType = "MES1";
}

if ( lines[0][0..7] == '654321' ||  lines[1][0..7] == '654321') {
    mesType = "MES2";
}

if ( lines[0][0..7] == '234561' ||  lines[1][0..7] == '234561') {
    mesType = "MES3";
}

message.setProperty('mesType', mesType);

return message.getPayload();

但是当我使用它时,在我的日志文件中出现了以下错误:

groovy.lang.MissingMethodException: No signature of method: [B.split() is applicable for argument types: (java.lang.String) values: {"\n"} (javax.script.ScriptException)

当我将分割线更改为以下内容时:

def lines = message.getPayload().toString().split("\n");

我遇到了一个数组越界的错误,所以看起来它仍然没有处理换行符。

收到的消息(message.getPayload)是来自文件系统的消息,其中包含换行符。它长这样:

ABCDFERGDSFF
123456SDFDSFDSFDSF
JGHJGHFHFH

我做错了什么?消息是通过Mule 2.X收集的。

2个回答

16

看起来 message.payload 返回的是一个 byte[] 数组,你需要将其转换成字符串:


Translated text:

看起来 message.payload 返回的是一个 byte[] 数组,你需要将其转换成字符串:

def lines = new String( message.payload, 'UTF-8' ).split( '\n' )

应该懂了 :-)

此外,我倾向于将这样的写法表达为:

def mesType = new String( message.payload, 'US-ASCII' ).split( '\n' ).take( 2 ).with { lines ->
    switch( lines ) {
        case { it.any { line -> line.startsWith( '123456' ) } } : 'MES1' ; break
        case { it.any { line -> line.startsWith( '654321' ) } } : 'MES2' ; break
        case { it.any { line -> line.startsWith( '234561' ) } } : 'MES3' ; break
        default :
          ''
    }
}

与其使用大量带有字符串范围访问的if...else块(例如:如果您得到一个只有3个字符或有效载荷中仅有1行的行,则您的代码将失败)

在Groovy 1.5.6中,你被限制为:

def mesType = new String( message.payload, 'US-ASCII' ).split( '\n' )[ 0..1 ].with { lines ->

保持乐观,希望负载至少有两行

否则你需要引入一种方法,将数组中的元素取出最多两个

您可以尝试:

可能是 with 导致 1.5.6 版本出现问题(不确定)... 尝试恢复到最初的状态:

def lines = new String( message.payload, 'US-ASCII' ).split( '\n' )[ 0..1 ]
def mesType = 'empty'
if(      lines.any { line -> line.startsWith( '123456' ) } ) mesType = 'MES1'
else if( lines.any { line -> line.startsWith( '654321' ) } ) mesType = 'MES2'
else if( lines.any { line -> line.startsWith( '234561' ) } ) mesType = 'MES3'

编码是否必要?这不是一个XML文件,而是一个ASCII文件,如果接收到的编码不是UTF-8,则需要进行编码。 - Mark Veenstra
啊啊啊...你使用的 Groovy 版本是多少? take 函数只在 Groovy 1.8.1 及以上版本中才添加到数组中。 - tim_yates
不太清楚。我们使用的是Mule 2.X,您知道其中包含哪个Groovy版本吗? - Mark Veenstra
看起来可能是2008年4月发布的Groovy v1.5.6... 叹气... 等等,我会想出一个替代方案的... - tim_yates
变量 mesType 保持为空(我用文本“空”填充了默认值)。看起来它没有循环遍历所有行。 - Mark Veenstra
显示剩余8条评论

3
def lines = "${message.getPayload()}".split('\n');

这种方法也应该适用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接