Groovy尝试在换行符上拆分时返回错误

Groovy尝试在换行符上拆分时返回错误,groovy,mule,Groovy,Mule,我是否尝试使用换行符拆分邮件并使用以下脚本: 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') {

我是否尝试使用换行符拆分邮件并使用以下脚本:

    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收集的。

看起来像
消息。有效负载
返回一个
字节[]
,您需要将其返回到字符串中:

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 ->
祈祷它的有效载荷至少有2条线

或者,您需要引入一个方法,从一个数组中获取最多2个元素

你能试试吗 可能是带的
正在突破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。通常最好指定一种编码方式。尝试
US-ASCII
当我使用您喜欢的解决方案时,它会说:
[Ljava.lang.String;.take()适用于参数类型:(java.lang.Integer)值:{2}(groovy.lang.MissingMethodException)
Ahhh…您使用的是什么版本的groovy?
take
只添加到groovy 1.8.1中的数组中,我不太清楚。我们使用Mule 2.X。您知道其中包括哪个groovy版本吗?
def lines = "${message.getPayload()}".split('\n');