kettle脚本中java代码-字符串转换⽤法
有时候kettle中的组件不能满⾜需求情况下,可以使⽤java代码组件实现,以下是实现读取⼀个⽂本⽂件,但是⽂本⽂件中的分割符是个数不等的空字符,⽐如空格,像转为⼀个空格,再拆分字符串数组。这⾥只是⼀个简单⽤法
环境是:kettle7.0
具体组件拖拉过程不详述,这⾥主要介绍重点部分
上图:
⽂本⽂件输⼊组件中指向的⽂本⽂件内容为:
gy  0.11  0.21 0.31
ny  0.12  0.22  0.32
qx  0.13 0.23          0.33
⽤户⾃定义java class组件内容为:
import java.util.*;
private String str1;
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
Object[] r = getRow();
// If the row object is null, we are done processing.
if (r == null) {
setOutputDone();
return false;
}
//String
str1 = get(Fields.In, "col1_col2__col3").getString(r);
//String str2 = placeAll("[ ]+", " ");
//String[] a1 = str2.split(" ");// 拆分为字符串数组
String[] a1 = to_Str_arr(str1);//调⽤函数执⾏字符拆分,当然也可以直接拆分这⾥是顺带演⽰调⽤函数
// 赋值给输出变量
String one = a1[0];
String two = a1[1];
String three = a1[2];
String four = a1[3];
/
/ 创建输出⾏,
Object[] outputRow = createOutputRow(r, data.outputRowMeta.size());
get(Fields.Out, "out_str1").setValue(outputRow, one);
get(Fields.Out, "out_str2").setValue(outputRow, two);
//putRow(data.outputRowMeta, outputRow2);
get(Fields.Out, "out_str3").setValue(outputRow, three);
//putRow(data.outputRowMeta, outputRow3);
get(Fields.Out, "out_str4").setValue(outputRow, four);
putRow(data.outputRowMeta, outputRow); // 输出⾏
return true;
}
java中split的用法/
/ 这⾥主要是将字符串转换为字符串数组,不过先将多个空格经过正则替换为⼀个
private String[] to_Str_arr(String str){
String str1 = str;
String str2 = placeAll("[ ]+", " ");
String[] a1 = str2.split(" ");
return a1;
}
关键部分已经说明,另外可以在函数中使⽤putRow⽣成新⾏,也就是前⼀个组件中有1⾏数据,这⾥可以创建n⾏数据来输出给后边的组件,相当于⽣成⾏记录组件;输出变量设置:
最后执⾏完结果为:
out_str1;out_str2;out_str3;out_str4 gy;0.11;0.21;0.31
ny;0.12;0.22;0.32
qx;0.13;0.23;0.33

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。