前篇关于Spring Batch的文章,讲述了Spring Batch 对XML文件的读写操作。 本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对固定长格式文件的读写操作。实例延续前面的例子,读取一个含有四个字段的TXT文件(ID,Name,Age,Score),对读取的字段做简单的处理,然后输出到另外一个TXT文件中。

工程结构如下图:

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

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

按 Ctrl+C 复制代码
<?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.1.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 name="lineMapper">
<bean:bean
class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<bean:property name="lineTokenizer" ref="lineTokenizer" />
<bean:property name="fieldSetMapper">
<bean:bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<bean:property name="prototypeBeanName" value="studentBean"/>
</bean:bean>
</bean:property>
</bean:bean>
</bean:property>
</bean:bean>
<bean:bean id="studentBean"
class="com.wanggc.springbatch.sample.fixedlength.StudentPojo" scope="prototype" />
<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 name="names" value="ID,name,age,score" />
</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 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:bean>
</bean:property>
<bean:property name="format" value="%-9s%-20s%3d%-2.0f" />
</bean:bean>
</bean:property>
</bean:bean>
</bean:beans>
按 Ctrl+C 复制代码

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

33-49行配置了读处理的详细信息。固定长格式和csv格式都属于flat文件格式,所以读取固定长格式文件也是需要使用Spring Batch提供的核心类FlatFileItemReader。对此类的配置在《Spring Batch 之 Sample(CSV文件操作)(四) 》中已经做过详细说明。但要注意lineTokenizer的配置,在读取CSV文件的时候,使用的是DelimitedLineTokenizer类,但是读取固定长格式的文件,需要使用FixedLengthTokenizer,如52-56行所示。其columns是如何分割一条记录信息,也就是说指定哪几列属于一个项目的信息(注意:列数的总长度与文件记录长度不一样的时候,会报错。注意限定范围)。属性names指定每个项目的名字。其名字与44行prototypeBeanName属性指定的Pojo属性名相同。

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

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

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 {
/* 合并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 com.wanggc.springbatch.sample.fixedlength;

/** Pojo类_Student */
public class StudentPojo {
/** ID */
private String ID = "";
/** 名字 */
private String name = "";
/** 年龄 */
private int age = 0;
/** 分数 */
private float score = 0;
/* 为节省篇幅,getter 和 setter 已经删除 */
}

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

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文件内容如下:

处理结果如下:

下次,将和大家一起讨论关于Spring Batch 对复合格式文件的读写问题。

作者:孤旅者
如果本文使您有所收获,请点击右下角的 [推荐]!
如果您对本文有意见或者建议,欢迎留言,哪怕是拍砖(^_^)!
欢迎转载,请注明出处!
感谢您的阅读,请关注后续博客!

SpringBatch Sample (四)(固定长格式文件读写)的更多相关文章

  1. SpringBatch Sample (五)(复合格式文件的读、多文件的写)

    前面关于Spring Batch的文章,讲述了SpringBatch对CSV文件的读写操作.对XML文件的操作,以及对固定长格式文件的操作.这些事例,同一个Reader读取的都是相同格式的数据,最终写 ...

  2. Linux长格式文件属性介绍

    长格式文件属性 查看长格式文件命令:ll (或ls -l) (1)-:文件类型 -:普通文件 d:目录 b:块设备文件(随机读取) c:字符设备文件(顺序读取) p:管道文件 s:Socket套接字文 ...

  3. SpringBatch Sample (三)(XML文件操作)

    前篇关于Spring Batch的文章,讲述了Spring Batch 对CSV文件的读写操作. 本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对XML文件的读写操作.实例流程是 ...

  4. SpringBatch Sample (二)(CSV文件操作)

    本文将通过一个完整的实例,与大家一起讨论运用Spring Batch对CSV文件的读写操作.此实例的流程是:读取一个含有四个字段的CSV文件(ID,Name,Age,Score),对读取的字段做简单的 ...

  5. 技能Get·Windows10将任何格式文件固定到开始屏幕

    阅文时长 | 0.6分钟 字数统计 | 960.8字符 主要内容 | 1.引言&背景 2.将文件加入到应用列表中 3.修改注册表法 4.声明与参考资料 『技能Get·Windows10将任何格 ...

  6. JAVA用geotools读写shape格式文件

    转自:http://toplchx.iteye.com/blog/1335007 JAVA用geotools读写shape格式文件 (对应geotools版本:2.7.2) (后面添加对应geotoo ...

  7. 《The Linux Command Line》 读书笔记03 ls命令与长格式输出解释 文件权限

    ls命令与长格式输出解释 文件权限 ls命令 ls 命令用于列出目录内容,不带参数时列出当前工作目录的内容,也可以指定目标目录(可以指定多个),列出目标目录下的内容. ls命令的参数 ls -l 长格 ...

  8. java将数据写入到txt文件中(txt有固定的格式)

    java将数据写入到txt文件中,这个应该对于学过java I/O的人来说是很简单的事情了,但是如果要将数据以固定的格式写入到txt文件中,就需要一定的技巧了. 这里举个简单的例子,以供参考: 比如我 ...

  9. C#读取固定文本格式的txt文件

    C#读取固定文本格式的txt文件 一个简单的C#读取txt文档的程序,文档中用固定的格式存放着实例数据. //判断关键字在文档中是否存在 ] == "设备ID:107157061" ...

随机推荐

  1. ccf碰撞的小球

    之前的代码有人运行不成功,自己又看了一下是输入变量顺序输入错了,现在是正确答案- #include<stdio.h> struct node{ int x; int dir; }; int ...

  2. 2017-5-19&5-23/系统性能指标

    1. 系统性能指标包括哪些? 业务指标.资源指标.中间件指标.数据库指标.前端指标.稳定性指标.批量处理指标.可扩展性指标.可靠性指标. 1)业务指标:主要包括并发用户数.响应时间.处理能力. 指标 ...

  3. Nginx反向代理配置教程(php-fpm)

    1.安装nginx http://www.cnblogs.com/lsdb/p/6543441.html 2.安装php-fpm yum install -y php-fpm 3.配置Nginx反向代 ...

  4. JAVA工程师面试常见问题集锦

    集锦一: 一.面试题基础总结 1. JVM结构原理.GC工作机制详解 答:具体参照:JVM结构.GC工作机制详解     ,说到GC,记住两点:1.GC是负责回收所有无任何引用对象的内存空间. 注意: ...

  5. socket简述-------转载

    “一切皆Socket!” 话虽些许夸张,但是事实也是,现在的网络编程几乎都是用的socket. ——有感于实际编程和开源项目研究. 我们深谙信息交流的价值,那网络中进程之间如何通信,如我们每天打开浏览 ...

  6. Consecutive Subsequence CodeForces - 977F(dp)

    Consecutive Subsequence CodeForces - 977F 题目大意:输出一序列中的最大的连续数列的长度和与其对应的下标(连续是指 7 8 9这样的数列) 解题思路: 状态:把 ...

  7. css制作tips提示框,气泡框,制作三角形

    有时候我们的页面会需要这样的一些提示框或者叫气泡框,运用css,我们可以实现这样的效果. 为了实现上面的效果,我们首先要理解如何制作三角形. 当我们给一个DIV不同颜色的边框的时候,我们可以得到下面的 ...

  8. QuickStart系列:docker部署之Mysql

    这里配置只做开发用,生产环境请根据需要修改或自行搜索其他说明 使用docker安装mysql,目前版本5.7.4(当前时间 2018.1.11) 环境 vm: Centos7 镜像来源 https:/ ...

  9. 用highchaarts做股票分时图

    1.首先向社区致敬给予灵感参考: https://bbs.hcharts.cn/thread-1985-1-1.html(给予参考的的例子js配置代码未进行压缩,可以清楚看到配置信息)   2.公司是 ...

  10. Uva LA 3902 - Network 树形DP 难度: 0

    题目 https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_pr ...