`
mowengaobo
  • 浏览: 164124 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Spring Batch 之 Sample(固定长格式文件读写)(六)

 
阅读更多

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

      工程结构如下图:

      applicationContext.xml和log4j.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.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>
 

       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 对复合格式文件的读写问题。

 

分享到:
评论

相关推荐

    spring Batch实现数据库大数据量读写

    在 `springBatchDemo` 文件中,通常包含了示例代码,演示如何配置和运行一个简单的Spring Batch作业,涉及到读取数据库中的数据,进行处理,然后写回到数据库。你可以参考这些代码,理解Spring Batch的工作原理和...

    Spring Batch读取txt文件并写入数据库的方法教程

    在本教程中,我们将探讨如何使用 Spring Batch 读取文本(txt)文件,并将读取到的数据处理后写入数据库。 首先,我们需要创建一个 Maven 项目,并在 `pom.xml` 文件中添加必要的依赖。这些依赖包括 `spring-boot-...

    Spring Batch in Action英文pdf版

    Spring Batch提供了多种内置的ItemReader和ItemWriter实现,支持从数据库、文件等多种数据源读取数据,以及将数据写入到数据库、文件等目的地。 知识点五:数据处理 在数据被读取之后,通常需要经过一定的处理才能...

    Spring Boot整合Spring Batch,实现批处理

    在这个提供的压缩包文件中,名为"batch"的文件可能包含了一个简单的Spring Boot和Spring Batch整合的示例项目。这些文件可能包括Java源代码、配置文件以及可能的测试用例。通过查看这些文件,你可以学习如何将批处理...

    SpringBatch+Spring+Mybatis+MySql (spring batch 使用jar)

    Spring Batch是一个轻量级的,完全面向Spring的批处理框架,可以应用于企业级大量的数据处理系统。Spring Batch以POJO和大家熟知的Spring框架为基础,使开发者更容易的访问和利用企业级服务。Spring Batch可以提供...

    Spring Batch学习demo项目源码

    在源码中,`batch-xml`文件可能是配置文件,通常在Spring Batch项目中,这些文件包含重要的作业(job)和步骤(step)配置。XML配置是Spring Batch早期版本常用的配置方式,尽管现代Spring Batch也支持Java配置和...

    quartz整合springbatch动态集群定时实现mysql参考

    Spring Batch可以通过配置文件或编程方式定义批处理作业的步骤和流程。 动态集群是指能够在运行时动态添加或移除服务器节点的集群环境。在Quartz中实现动态集群,主要是通过共享JobStore实现的,例如使用...

    spring-batch分区处理示例

    6. **配置文件**:通常,这些配置会在Spring Batch的XML或Java配置文件中定义,包括Job、Step、Partitioner、TaskExecutor以及其他相关组件的设置。 在这个示例中,我们可能会看到如何通过XML或Java配置实现上述...

    Spring Batch批处理框架

    Spring Batch的事务管理是其核心特性之一。Spring Batch要求每个步骤都运行在一个事务上下文中。事务保证了步骤中进行的操作要么全部成功,要么全部回滚,这为批处理作业提供了数据一致性和完整性保障。 4. 错误...

    springbatch 详解PDF附加 全书源码 压缩包

    **Spring Batch 深度解析** Spring Batch 是一个强大的、全面的批处理框架,由 Spring 社区开发,旨在简化企业级应用中的批量数据处理任务。这个框架提供了一种标准的方式来处理大量的数据输入和输出,使得开发者...

    SpringBatch的简单Sample

    在"SpringBatch的简单Sample"中,我们将探讨两种主要的处理模式:Tasklet和Chunk。 1. **Tasklet**: Tasklet 是SpringBatch中的基本执行单元,它可以被视为一个独立的任务。Tasklet 不是基于数据集的,而是执行一...

    spring-batch包

    在压缩包文件 `spring-batch-4.0.0.M5` 中,包含了 Spring Batch 4.0.0 版本的预发布版本。这个版本可能包含了一些实验性的特性和改进,用于测试和反馈,以便在正式版中进行完善。 总的来说,Spring Batch 4.0.0 为...

    Spring batch in action

    Spring Batch提供了强大的读取器和写入器实现,这些实现支持多种数据源和格式,包括关系型数据库、文件系统和消息队列等。读取器通过ItemReader接口读取数据项,写入器通过ItemWriter接口将处理后的数据写入目标系统...

    The Definitive Guide to Spring Batch, 2nd Edition.epub

    Work with all aspects of batch processing in a modern Java environment using a selection of Spring frameworks. This book provides up-to-date examples using the latest configuration techniques based on...

    基于Spring Batch的大数据量并行处理

    ### 基于Spring Batch的大数据量并行处理 #### 概述 Spring Batch是一款用于高效处理大量数据的开源框架,特别适用于批处理任务。它由Spring Source与Accenture合作开发,结合了双方在批处理架构和技术上的优势,...

    Spring.Batch批处理框架

    Spring Batch是Spring的一个子项目,使用Java语言并基于Spring框架为基础开发,使得已经使用 Spring 框架的开发者或者企业更容易访问和利用企业服务。 Spring Batch 提供了大量可重用的组件,包括了日志、追踪、事务、...

    Spring Batch In Action

    #### 知识点六:Spring Batch 的高级特性 - **分片(Partitioning)**:Spring Batch 支持将大型批处理任务分割成更小的子任务并行处理,以提高整体处理效率。 - **重启能力**:当 Job 因故中断时,Spring Batch ...

    SpringBatch-HelloWorld

    SpringBatch Tasklet sample

    springBoot+springBatch批量处理数据demo

    在`pom.xml`或`build.gradle`文件中添加依赖后,SpringBoot会自动加载SpringBatch的配置。 接着,SpringBatch的主要组件包括Job、Step、Tasklet、ItemReader、ItemWriter和ItemProcessor。Job是批处理任务的高层次...

    Spring Batch API(Spring Batch 开发文档).CHM

    Spring Batch API(Spring Batch 开发文档).CHM。 官网 Spring Batch API,Spring Batch 开发文档

Global site tag (gtag.js) - Google Analytics