Spring Batch 之 Sample(固定長格式文(wen)件(jian)讀(du)寫)(六)
前篇關于Spring Batch的文章,講述了Spring Batch 對XML文件的讀寫操作。 本文(wen)將通過一(yi)個完整的實(shi)例,與大家一(yi)起討論運(yun)用(yong)Spring Batch對固定長格(ge)式文(wen)件的讀(du)寫操作。實(shi)例延續前面的例子,讀(du)取一(yi)個含有四個字段的TXT文(wen)件(ID,Name,Age,Score),對讀(du)取的字段做簡單的處理,然(ran)后輸出(chu)到另外一(yi)個TXT文(wen)件中。
工程結構如下圖(tu):

applicationContext.xml和log4j.xml前文已經敘(xu)述(shu)過,在此(ci)不做贅(zhui)述(shu)。
本(ben)文(wen)核心配(pei)置(zhi)文(wen)件batch.xml內容如(ru)下:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <bean:beans xmlns="//www.springframework.org/schema/batch"
3 xmlns:bean="//www.springframework.org/schema/beans" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
4 xmlns:p="//www.springframework.org/schema/p" xmlns:tx="//www.springframework.org/schema/tx"
5 xmlns:aop="//www.springframework.org/schema/aop" xmlns:context="//www.springframework.org/schema/context"
6 xmlns:util="//www.springframework.org/schema/util"
7 xsi:schemaLocation="//www.springframework.org/schema/beans
8 //www.springframework.org/schema/beans/spring-beans-3.0.xsd
9 //www.springframework.org/schema/tx
10 //www.springframework.org/schema/tx/spring-tx-3.0.xsd
11 //www.springframework.org/schema/aop
12 //www.springframework.org/schema/aop/spring-aop-3.0.xsd
13 //www.springframework.org/schema/context
14 //www.springframework.org/schema/context/spring-context-2.5.xsd
15 //www.springframework.org/schema/batch
16 //www.springframework.org/schema/batch/spring-batch-2.1.xsd
17 //www.springframework.org/schema/util //www.springframework.org/schema/util/spring-util.xsd">
18
19 <bean:import resource="applicationContext.xml" />
20
21 <!-- Job信(xin)息的配置 -->
22 <job id="fixedLengthJob">
23 <step id="fixedLengthStep">
24 <tasklet>
25 <chunk reader="fixedLengthReader" writer="fixedLengthWriter"
26 processor="fixedLengthProcessor" commit-interval="10">
27 </chunk>
28 </tasklet>
29 </step>
30 </job>
31
32 <!-- 固定長(chang)文件的讀(du)信息的配(pei)置 -->
33 <bean:bean id="fixedLengthReader"
34 class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
35 <bean:property name="resource"
36 value="file:#{jobParameters['inputFilePath']}" />
37 <bean:property name="lineMapper">
38 <bean:bean
39 class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
40 <bean:property name="lineTokenizer" ref="lineTokenizer" />
41 <bean:property name="fieldSetMapper">
42 <bean:bean
43 class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
44 <bean:property name="prototypeBeanName" value="studentBean"/>
45 </bean:bean>
46 </bean:property>
47 </bean:bean>
48 </bean:property>
49 </bean:bean>
50 <bean:bean id="studentBean"
51 class="com.wanggc.springbatch.sample.fixedlength.StudentPojo" scope="prototype" />
52 <bean:bean id="lineTokenizer"
53 class="org.springframework.batch.item.file.transform.FixedLengthTokenizer">
54 <bean:property name="columns" value="1-6,7-15,16-18,19-" />
55 <bean:property name="names" value="ID,name,age,score" />
56 </bean:bean>
57
58 <!-- 固定長(chang)格式文件的(de)寫 -->
59 <bean:bean id="fixedLengthWriter"
60 class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
61 <bean:property name="resource"
62 value="file:#{jobParameters['outputFilePath']}" />
63 <bean:property name="lineAggregator">
64 <bean:bean
65 class="org.springframework.batch.item.file.transform.FormatterLineAggregator">
66 <bean:property name="fieldExtractor">
67 <bean:bean
68 class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
69 <bean:property name="names" value="ID,name,age,score" />
70 </bean:bean>
71 </bean:property>
72 <bean:property name="format" value="%-9s%-20s%3d%-2.0f" />
73 </bean:bean>
74 </bean:property>
75 </bean:bean>
76 </bean:beans>
22-30行(xing)配置了(le)Job的基本(ben)(ben)信息。此Job包含一個Step,Step中(zhong)包含了(le)基本(ben)(ben)的讀(fixedLengthReader),處理(fixedLengthProcessor),寫(fixedLengthWriter)以及commit件(jian)數(commit-interval)。
33-49行配置了讀處理的詳細信息。固定長格式和csv格式都屬于flat文件格式,所以讀取固定長格式文件也是需要使用Spring Batch提供的核心類FlatFileItemReader。對此類的配置在《Spring Batch 之 Sample(CSV文件操作)(四) 》中已(yi)經做過(guo)詳細(xi)說(shuo)明。但要(yao)注(zhu)意lineTokenizer的(de)(de)配置(zhi),在讀取CSV文(wen)件(jian)(jian)(jian)的(de)(de)時(shi)候(hou),使用(yong)(yong)的(de)(de)是(shi)DelimitedLineTokenizer類,但是(shi)讀取固定長格(ge)式(shi)的(de)(de)文(wen)件(jian)(jian)(jian),需要(yao)使用(yong)(yong)FixedLengthTokenizer,如(ru)52-56行所示。其(qi)columns是(shi)如(ru)何分割一(yi)(yi)條記(ji)錄(lu)信(xin)息,也就是(shi)說(shuo)指(zhi)定哪幾列(lie)屬(shu)于一(yi)(yi)個項目的(de)(de)信(xin)息(注(zhu)意:列(lie)數的(de)(de)總長度與文(wen)件(jian)(jian)(jian)記(ji)錄(lu)長度不一(yi)(yi)樣的(de)(de)時(shi)候(hou),會報錯。注(zhu)意限定范圍)。屬(shu)性(xing)names指(zhi)定每個項目的(de)(de)名(ming)字。其(qi)名(ming)字與44行prototypeBeanName屬(shu)性(xing)指(zhi)定的(de)(de)Pojo屬(shu)性(xing)名(ming)相同(tong)。
59-76行(xing)配置了寫(xie)處(chu)理的詳細信息。寫(xie)固定(ding)長(chang)格式的文(wen)件,與寫(xie)CSV格式的文(wen)件一樣(yang),也是使用(yong)Spring Batch提供(gong)的核(he)心類FlatFileItemWriter。在此也不再贅述(shu)。但要注(zhu)意lineAggregator屬(shu)性(xing)使用(yong)的是FormatterLineAggregator類,此類的format屬(shu)性(xing)可以(yi)指定(ding)每個項目所占的長(chang)度(du)和格式。
batch.xml文件配置了(le)對固定(ding)長(chang)文件的(de)(de)和寫。在讀之后,寫之前的(de)(de)處理,是(shi)通過(guo)自定(ding)的(de)(de)FixedLengthProcessor 類處理的(de)(de)。詳(xiang)細代碼如下(xia):
package com.wanggc.springbatch.sample.fixedlength;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;
/**
* 業務處理類。
*
* @author Wanggc
*/
@Component("fixedLengthProcessor")
public class FixedLengthProcessor implements
ItemProcessor<StudentPojo, StudentPojo> {
/**
* 對取到的數據進行簡單的處理。
*
* @param student
* 處理前的數據。
* @return 處理后的數據。
* @exception Exception
* 處理是發生的任何異常。
*/
public StudentPojo process(StudentPojo student) throws Exception {
/* 合(he)并ID和(he)名字(zi) */
student.setName(student.getID() + "--" + student.getName());
/* 年齡(ling)加2 */
student.setAge(student.getAge() + 2);
/* 分數加10 */
student.setScore(student.getScore() + 10);
/* 將處理后的(de)結果(guo)傳遞(di)給(gei)writer */
return student;
}
}
至(zhi)此,對固定長格式文(wen)件的讀、處理、寫操作已(yi)經介紹完畢(bi)。下面是一(yi)些輔助文(wen)件的信(xin)息。
Pojo類StudentPojo的詳細(xi)代碼如下(xia):
package com.wanggc.springbatch.sample.fixedlength;
/** Pojo類_Student */
public class StudentPojo {
/** ID */
private String ID = "";
/** 名字 */
private String name = "";
/** 年齡(ling) */
private int age = 0;
/** 分(fen)數 */
private float score = 0;
/* 為節(jie)省篇幅,getter 和 setter 已經刪(shan)除 */
}
Job啟動類Launch的詳細代碼(ma)如下:
package com.wanggc.springbatch.sample.fixedlength;
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 {
// JOB實行
JobExecution result = launcher.run(
job,
new JobParametersBuilder()
.addString("inputFilePath",
"C:\\testData\\fixedLengthInputFile.txt")
.addString("outputFilePath",
"C:\\testData\\fixedLengthOutputFile.txt")
.toJobParameters());
// 運行結果輸出
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
input文件內容如(ru)下(xia):

處理結果如下(xia):

下次,將(jiang)和(he)大家一起討(tao)論(lun)關于Spring Batch 對復(fu)合格式文件的讀(du)寫問(wen)題。
歡迎轉載,請注明出處!
感謝您的閱讀,請關注后續博客!
共享視頻教程請訪問:
