您的位置:首页 > 编程语言 > Java开发

SpringBatch之固定长格式文件读写

2013-10-14 14:36 453 查看
在看本篇博客之前,希望您能先到http://xuanmeiku.taobao.com去转转,里面全是真皮炫美酷时尚女鞋,价格实惠!如果你看中了哪一款,可以加我qq1074992674,或者直接通过旺旺联系我!欢迎大家的骚扰!本人诚信经营,绝不做欺骗他人的事情!

本文主要通过一个完整的实例,运用Spring Batch对固定长格式文件的读写操作。实例延续前面的例子,读取一个含有四个字段(ID,NAME,AGE,SCORE),对读取的字段做简单的处理,然后输出到两外一个TXT文件中。

工程结构如下图:



applicationContext.xml前文已经叙述过,在此不做阐述。

本文核心配置文件batch.xml的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns="http://www.springframework.org/schema/batch"
xmlns:bean="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
<bean:import resource="applicationContext.xml" />

<!-- Job信息的配置 -->
<job id="fixedLengthJob">
<step id="fixedLengthStep">
<tasklet>
<chunk reader="fixedLengthReader" writer="fixedLengthWriter"
processor="fixedLengthProcessor" commit-interval="10">
</chunk>
</tasklet>
</step>
</job>

<!-- 固定长格式文件的读信息的配置 -->
<bean:bean id="fixedLengthReader"
class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
<bean:property name="resource" value="file:#{jobParameters['inputFilePath']}"></bean:property>
<bean:property name="lineMapper">
<bean:bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<bean:property name="lineTokenizer" ref="lineTokenizer"></bean:property>
<bean:property name="fieldSetMapper">
<bean:bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<bean:property name="prototypeBeanName" value="studentBean"></bean:property>
</bean:bean>
</bean:property>
</bean:bean>
</bean:property>
</bean:bean>

<bean:bean id="studentBean" class="cn.lichunan.springbatch.pojo.StudentPojo" scope="prototype"></bean:bean>

<bean:bean id="lineTokenizer" class="org.springframework.batch.item.file.transform.FixedLengthTokenizer">
<bean:property name="columns" value="1-6,7-15,16-18,19-"></bean:property>
<bean:property name="names" value="ID,name,age,score"></bean:property>
</bean:bean>

<!-- 固定长格式文件的写 -->
<bean:bean id="fixedLengthWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<bean:property name="resource" value="file:#{jobParameters['outputFilePath']}"></bean:property>
<bean:property name="lineAggregator">
<bean:bean class="org.springframework.batch.item.file.transform.FormatterLineAggregator">
<bean:property name="fieldExtractor">
<bean:bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<bean:property name="names" value="ID,name,age,score"></bean:property>
</bean:bean>
</bean:property>
<bean:property name="format" value="%-9s%-20s%3d%-2.0f"></bean:property>
</bean:bean>
</bean:property>
</bean:bean>

</bean:beans>

此Job包含一个Step,Step中包含了基本的读(fixedLengthReader),处理(fixedLengthProcessor),写(fixedLengthWriter)以及commit件数(commit-interval)。

固定长格式和csv格式都属于flat文件格式,所以读取固定长格式文件也是需要使用Spring Batch提供的核心类FlatFileItemReader。但要注意lineTokenizer的配置,在读取CSV文件的时候,使用的是DelimitedLineTokenizer类,但是读取固定长格式的文件,需要使用FixedLengthTokenizer。其columns是如何分割一条记录信息,也就是说指定哪几列属于一个项目的信息(注意:列数的总长度与文件记录长度不一样的时候,会报错。注意限定范围)。属性names指定每个项目的名字。

写固定长格式的文件,与写CSV格式的文件一样,也是使用Spring Batch提供的核心类FlatFileItemWriter。在此也不再赘述。但要注意lineAggregator属性使用的是FormatterLineAggregator类,此类的format属性可以指定每个项目所占的长度和格式。

batch.xml文件配置了对固定长文件的和写。在读之后,写之前的处理,是通过自定的FixedLengthProcessor 类处理的。详细代码如下:

package cn.lichunan.springbatch.processor;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;

import cn.lichunan.springbatch.pojo.StudentPojo;

/**
* 业务处理类
* @author soft
*
*/
@Component("fixedLengthProcessor")
public class FixedLengthProcessor implements ItemProcessor<StudentPojo, StudentPojo> {

/**
* 对取到的数据进行简单的处理
*
* @param student 处理前的数据
* @return 处理后的数据
* @exception Exception 处理的是发生的任何异常
*/
public StudentPojo process(StudentPojo student) throws Exception {
/**合并ID和名字*/
student.setName(student.getID() + "--" + student.getName());
/**年龄加2*/
student.setAge(student.getAge() + 2);
/**分数加10*/
student.setScore(student.getScore() + 10);
/**将处理后的结果返回给writer*/
return student;
}

}

Pojo类StudentPojo的详细代码如下:

package cn.lichunan.springbatch.pojo;

/**
* Pojo类_Student
*
* @author soft
*
*/
public class StudentPojo {
/** ID */
private String ID;
/** 名字 */
private String name;
/** 年龄 */
private int age;
/** 分数 */
private float score;

public String getID() {
return ID;
}

public void setID(String iD) {
ID = iD;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public float getScore() {
return score;
}

public void setScore(float score) {
this.score = score;
}

}

Job启动类Launch的详细代码如下:

package cn.lichunan.springbatch.launch;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Launch {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"batch.xml");
JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("fixedLengthJob");
try {
JobExecution result = launcher.run(
job,
new JobParametersBuilder()
.addString(
"inputFilePath",
"E:\\workspace-springbatch\\springbat-FixedLength\\src\\main\\resource\\fixedLengthInputFile.txt")
.addString(
"outputFilePath",
"E:\\workspace-springbatch\\springbat-FixedLength\\src\\main\\resource\\fixedLengthOutputFile.txt")
.toJobParameters());
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

}

input文件内容如下:

200001ZhangSan 17 78
200002LiSi     19 79
200003WangWu   20 80
200004ZhaoLiu  16 81
200005QianQi   19 82
200006LiuBa    18 83

处理结果如下:

200001   200001--ZhangSan     1988
200002   200002--LiSi         2189
200003   200003--WangWu       2290
200004   200004--ZhaoLiu      1891
200005   200005--QianQi       2192
200006   200006--LiuBa        2093
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: