原文:https://howtodoinjava.com/spring-batch/flatfileitemwriter-write-to-csv-file/

学习使用FlatFileItemWriter写入 CSV 数据。 它是将数据写入文件或流的项目编写器。 输出文件的位置由Resource定义,并且必须表示可写文件。

项目结构

在这个项目中,我们将学习:

  1. 使用MultiResourceItemReaderinput/*.csv读取 3 个 CSV 文件。
  2. 使用FlatFileItemWriter将整个数据写入output/outputData.csv文件。

Spring Batch `FlatFileItemWriter` – 写入 CSV 文件 - 图1

项目结构

使用FlatFileItemWriter写入数据 CSV 文件

您需要使用FlatFileItemWriter写入从 CSV 文件读取的行。 它将内容写入传递给writer.setResource()方法的任何Resource

BatchConfig.java

  1. package com.howtodoinjava.demo.config;
  2. import org.springframework.batch.core.Job;
  3. import org.springframework.batch.core.Step;
  4. import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
  5. import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
  6. import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
  7. import org.springframework.batch.core.launch.support.RunIdIncrementer;
  8. import org.springframework.batch.item.file.FlatFileItemReader;
  9. import org.springframework.batch.item.file.FlatFileItemWriter;
  10. import org.springframework.batch.item.file.MultiResourceItemReader;
  11. import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
  12. import org.springframework.batch.item.file.mapping.DefaultLineMapper;
  13. import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
  14. import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
  15. import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.beans.factory.annotation.Value;
  18. import org.springframework.context.annotation.Bean;
  19. import org.springframework.context.annotation.Configuration;
  20. import org.springframework.core.io.FileSystemResource;
  21. import org.springframework.core.io.Resource;
  22. import com.howtodoinjava.demo.model.Employee;
  23. @Configuration
  24. @EnableBatchProcessing
  25. public class BatchConfig
  26. {
  27. @Autowired
  28. private JobBuilderFactory jobBuilderFactory;
  29. @Autowired
  30. private StepBuilderFactory stepBuilderFactory;
  31. @Value("input/inputData*.csv")
  32. private Resource[] inputResources;
  33. private Resource outputResource = new FileSystemResource("output/outputData.csv");
  34. @Bean
  35. public FlatFileItemWriter<Employee> writer()
  36. {
  37. //Create writer instance
  38. FlatFileItemWriter<Employee> writer = new FlatFileItemWriter<>();
  39. //Set output file location
  40. writer.setResource(outputResource);
  41. //All job repetitions should "append" to same output file
  42. writer.setAppendAllowed(true);
  43. //Name field values sequence based on object properties
  44. writer.setLineAggregator(new DelimitedLineAggregator<Employee>() {
  45. {
  46. setDelimiter(",");
  47. setFieldExtractor(new BeanWrapperFieldExtractor<Employee>() {
  48. {
  49. setNames(new String[] { "id", "firstName", "lastName" });
  50. }
  51. });
  52. }
  53. });
  54. return writer;
  55. }
  56. @Bean
  57. public Job readCSVFilesJob() {
  58. return jobBuilderFactory
  59. .get("readCSVFilesJob")
  60. .incrementer(new RunIdIncrementer())
  61. .start(step1())
  62. .build();
  63. }
  64. @Bean
  65. public Step step1() {
  66. return stepBuilderFactory.get("step1").<Employee, Employee>chunk(5)
  67. .reader(multiResourceItemReader())
  68. .writer(writer())
  69. .build();
  70. }
  71. @Bean
  72. public MultiResourceItemReader<Employee> multiResourceItemReader()
  73. {
  74. MultiResourceItemReader<Employee> resourceItemReader = new MultiResourceItemReader<Employee>();
  75. resourceItemReader.setResources(inputResources);
  76. resourceItemReader.setDelegate(reader());
  77. return resourceItemReader;
  78. }
  79. @SuppressWarnings({ "rawtypes", "unchecked" })
  80. @Bean
  81. public FlatFileItemReader<Employee> reader()
  82. {
  83. //Create reader instance
  84. FlatFileItemReader<Employee> reader = new FlatFileItemReader<Employee>();
  85. //Set number of lines to skips. Use it if file has header rows.
  86. reader.setLinesToSkip(1);
  87. //Configure how each line will be parsed and mapped to different values
  88. reader.setLineMapper(new DefaultLineMapper() {
  89. {
  90. //3 columns in each row
  91. setLineTokenizer(new DelimitedLineTokenizer() {
  92. {
  93. setNames(new String[] { "id", "firstName", "lastName" });
  94. }
  95. });
  96. //Set values in Employee class
  97. setFieldSetMapper(new BeanWrapperFieldSetMapper<Employee>() {
  98. {
  99. setTargetType(Employee.class);
  100. }
  101. });
  102. }
  103. });
  104. return reader;
  105. }
  106. }

Employee.java

  1. public class Employee {
  2. String id;
  3. String firstName;
  4. String lastName;
  5. //public setter and getter methods
  6. }

inputData1.csv

  1. id,firstName,lastName
  2. 1,Lokesh,Gupta
  3. 2,Amit,Mishra
  4. 3,Pankaj,Kumar
  5. 4,David,Miller

inputData2.csv

  1. id,firstName,lastName
  2. 5,Ramesh,Gupta
  3. 6,Vineet,Mishra
  4. 7,Amit,Kumar
  5. 8,Dav,Miller

inputData3.csv

  1. id,firstName,lastName
  2. 9,Vikas,Kumar
  3. 10,Pratek,Mishra
  4. 11,Brian,Kumar
  5. 12,David,Cena

Maven 依赖

查看项目依赖项。

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.howtodoinjava</groupId>
  6. <artifactId>App</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9. <name>App</name>
  10. <url>http://maven.apache.org</url>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>2.0.3.RELEASE</version>
  15. </parent>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-batch</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>com.h2database</groupId>
  26. <artifactId>h2</artifactId>
  27. <scope>runtime</scope>
  28. </dependency>
  29. </dependencies>
  30. <build>
  31. <plugins>
  32. <plugin>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-maven-plugin</artifactId>
  35. </plugin>
  36. </plugins>
  37. </build>
  38. <repositories>
  39. <repository>
  40. <id>repository.spring.release</id>
  41. <name>Spring GA Repository</name>
  42. <url>http://repo.spring.io/release</url>
  43. </repository>
  44. </repositories>
  45. </project>

示例

在运行该应用程序之前,请查看App.java的完整代码,该代码将其作为 Spring Boot 应用程序运行。

App.java

  1. package com.howtodoinjava.demo;
  2. import org.springframework.batch.core.Job;
  3. import org.springframework.batch.core.JobParameters;
  4. import org.springframework.batch.core.JobParametersBuilder;
  5. import org.springframework.batch.core.launch.JobLauncher;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.SpringApplication;
  8. import org.springframework.boot.autoconfigure.SpringBootApplication;
  9. import org.springframework.scheduling.annotation.EnableScheduling;
  10. import org.springframework.scheduling.annotation.Scheduled;
  11. @SpringBootApplication
  12. @EnableScheduling
  13. public class App
  14. {
  15. @Autowired
  16. JobLauncher jobLauncher;
  17. @Autowired
  18. Job job;
  19. public static void main(String[] args)
  20. {
  21. SpringApplication.run(App.class, args);
  22. }
  23. @Scheduled(cron = "0 */1 * * * ?")
  24. public void perform() throws Exception
  25. {
  26. JobParameters params = new JobParametersBuilder()
  27. .addString("JobID", String.valueOf(System.currentTimeMillis()))
  28. .toJobParameters();
  29. jobLauncher.run(job, params);
  30. }
  31. }

application.properties

  1. #Disable batch job's auto start
  2. spring.batch.job.enabled=false
  3. spring.main.banner-mode=off

运行应用程序

将应用程序作为 Spring 运行应用程序运行,并观察控制台。 批处理作业将在每分钟开始时开始。 它将读取输入文件,并在控制台中打印读取的值。

outputData.csv

  1. 1,Lokesh,Gupta
  2. 2,Amit,Mishra
  3. 3,Pankaj,Kumar
  4. 4,David,Miller
  5. 5,Ramesh,Gupta
  6. 6,Vineet,Mishra
  7. 7,Amit,Kumar
  8. 8,Dav,Miller
  9. 9,Vikas,Kumar
  10. 10,Pratek,Mishra
  11. 11,Brian,Kumar
  12. 12,David,Cena

将我的问题放在评论部分。

学习愉快!