原文: https://howtodoinjava.com/spring-batch/flatfileitemreader-read-csv-example/

学习使用FlatFileItemReader类从文件系统或资源文件夹中读取 CSV 文件。

项目结构

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

  1. input/inputData.csv读取 CSV 文件。
  2. 将数据写入控制台。

Spring Batch `FlatFileItemReader` – 读取 CSV 示例 - 图1

项目结构

使用FlatFileItemReader读取 CSV

您需要使用FlatFileItemReader从 CSV 文件中读取行。

BatchConfig.java

  1. @Bean
  2. public FlatFileItemReader<Employee> reader()
  3. {
  4. //Create reader instance
  5. FlatFileItemReader<Employee> reader = new FlatFileItemReader<Employee>();
  6. //Set input file location
  7. reader.setResource(new FileSystemResource("input/inputData.csv"));
  8. //Set number of lines to skips. Use it if file has header rows.
  9. reader.setLinesToSkip(1);
  10. //Configure how each line will be parsed and mapped to different values
  11. reader.setLineMapper(new DefaultLineMapper() {
  12. {
  13. //3 columns in each row
  14. setLineTokenizer(new DelimitedLineTokenizer() {
  15. {
  16. setNames(new String[] { "id", "firstName", "lastName" });
  17. }
  18. });
  19. //Set values in Employee class
  20. setFieldSetMapper(new BeanWrapperFieldSetMapper<Employee>() {
  21. {
  22. setTargetType(Employee.class);
  23. }
  24. });
  25. }
  26. });
  27. return reader;
  28. }

inputData.csv

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

将读取的行写入控制台

创建实现ItemWriter接口的ConsoleItemWriter类。

ConsoleItemWriter.java

  1. import java.util.List;
  2. import org.springframework.batch.item.ItemWriter;
  3. public class ConsoleItemWriter<T> implements ItemWriter<T> {
  4. @Override
  5. public void write(List<? extends T> items) throws Exception {
  6. for (T item : items) {
  7. System.out.println(item);
  8. }
  9. }
  10. }

使用ConsoleItemWriter作为编写器。

BatchConfig.java

  1. @Bean
  2. public ConsoleItemWriter<Employee> writer()
  3. {
  4. return new ConsoleItemWriter<Employee>();
  5. }

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>

示例

在运行该应用程序之前,请查看BatchConfig.java的完整代码。

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.mapping.BeanWrapperFieldSetMapper;
  10. import org.springframework.batch.item.file.mapping.DefaultLineMapper;
  11. import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.core.io.FileSystemResource;
  16. import com.howtodoinjava.demo.model.Employee;
  17. @Configuration
  18. @EnableBatchProcessing
  19. public class BatchConfig
  20. {
  21. @Autowired
  22. private JobBuilderFactory jobBuilderFactory;
  23. @Autowired
  24. private StepBuilderFactory stepBuilderFactory;
  25. @Bean
  26. public Job readCSVFilesJob() {
  27. return jobBuilderFactory
  28. .get("readCSVFilesJob")
  29. .incrementer(new RunIdIncrementer())
  30. .start(step1())
  31. .build();
  32. }
  33. @Bean
  34. public Step step1() {
  35. return stepBuilderFactory.get("step1").<Employee, Employee>chunk(5)
  36. .reader(reader())
  37. .writer(writer())
  38. .build();
  39. }
  40. @SuppressWarnings({ "rawtypes", "unchecked" })
  41. @Bean
  42. public FlatFileItemReader<Employee> reader()
  43. {
  44. //Create reader instance
  45. FlatFileItemReader<Employee> reader = new FlatFileItemReader<Employee>();
  46. //Set input file location
  47. reader.setResource(new FileSystemResource("input/inputData.csv"));
  48. //Set number of lines to skips. Use it if file has header rows.
  49. reader.setLinesToSkip(1);
  50. //Configure how each line will be parsed and mapped to different values
  51. reader.setLineMapper(new DefaultLineMapper() {
  52. {
  53. //3 columns in each row
  54. setLineTokenizer(new DelimitedLineTokenizer() {
  55. {
  56. setNames(new String[] { "id", "firstName", "lastName" });
  57. }
  58. });
  59. //Set values in Employee class
  60. setFieldSetMapper(new BeanWrapperFieldSetMapper<Employee>() {
  61. {
  62. setTargetType(Employee.class);
  63. }
  64. });
  65. }
  66. });
  67. return reader;
  68. }
  69. @Bean
  70. public ConsoleItemWriter<Employee> writer()
  71. {
  72. return new ConsoleItemWriter<Employee>();
  73. }
  74. }

Employee.java

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

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 运行应用程序运行,并观察控制台。 批处理作业将在每分钟开始时开始。 它将读取输入文件,并在控制台中打印读取的值。

Console

  1. 2018-07-10 13:28:35 INFO - Starting App on FFC15B4E9C5AA with PID 12060 (C:\Users\user\app\App\target\classes started by zkpkhua in C:\Users\user\app\App)
  2. 2018-07-10 13:28:35 INFO - No active profile set, falling back to default profiles: default
  3. 2018-07-10 13:28:35 INFO - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@75329a49: startup date [Tue Jul 10 13:28:35 IST 2018]; root of context hierarchy
  4. 2018-07-10 13:28:37 INFO - HikariPool-1 - Starting...
  5. 2018-07-10 13:28:38 INFO - HikariPool-1 - Start completed.
  6. 2018-07-10 13:28:38 INFO - No database type set, using meta data indicating: H2
  7. 2018-07-10 13:28:38 INFO - No TaskExecutor has been set, defaulting to synchronous executor.
  8. 2018-07-10 13:28:39 INFO - Executing SQL script from class path resource [org/springframework/batch/core/schema-h2.sql]
  9. 2018-07-10 13:28:39 INFO - Executed SQL script from class path resource [org/springframework/batch/core/schema-h2.sql] in 74 ms.
  10. 2018-07-10 13:28:39 INFO - Registering beans for JMX exposure on startup
  11. 2018-07-10 13:28:39 INFO - Bean with name 'dataSource' has been autodetected for JMX exposure
  12. 2018-07-10 13:28:39 INFO - Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
  13. 2018-07-10 13:28:39 INFO - No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
  14. 2018-07-10 13:28:39 INFO - Started App in 4.485 seconds (JVM running for 5.33)
  15. 2018-07-10 13:29:00 INFO - Job: [SimpleJob: [name=readCSVFilesJob]] launched with the following parameters: [{JobID=1531209540004}]
  16. 2018-07-10 13:29:00 INFO - Executing step: [step1]
  17. Employee [id=1, firstName=Lokesh, lastName=Gupta]
  18. Employee [id=2, firstName=Amit, lastName=Mishra]
  19. Employee [id=3, firstName=Pankaj, lastName=Kumar]
  20. Employee [id=4, firstName=David, lastName=Miller]
  21. 2018-07-10 13:29:00 INFO - Job: [SimpleJob: [name=readCSVFilesJob]] completed with the following parameters: [{JobID=1531209540004}] and the following status: [COMPLETED]

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

学习愉快!