Framework/Spring-Batch

(10-1) Spring Batch FlatFileItemWriter

조훙 2022. 11. 16. 17:20

FlatFileItemWriter

  • Chunk List 단위로 데이터를 받아 일괄 출력 작업용 인터페이스
  • 지원 인터페이스
    • FlatFile
    • XML
    • Database
    • JMS, Message Queue
    • Custom Writer

고정형 FlatFileItemWriter Sample

@Bean
@StepScope
public FlatFileItemWriter<Customer> itemWriter(
        @Value("#{jobParameters['outputFile']}") Resource outputFile) {
    return new FlatFileItemWriterBuilder<Customer>()
            .name("customerItemWriter")
            .resource(outputFile)
            .formatted()
            .format("%s %s lives at %s %s in %s, %s.")
            .names(new String[] {
                    "firstName",
                    "lastName",
                    "address",
                    "city",
                    "state",
                    "zip"
            })
            .build();
}

Output 결과 예시

$ cat ./Chapter09/target/classes/output/formattedCustomers.txt
Richard Darrow lives at 5570 Isabella Ave St. Louis in IL, 58540.
Warren Darrow lives at 4686 Mt. Lee Drive St. Louis in NY, 94935.
Barack Donnelly lives at 7844 S. Greenwood Ave Houston in CA, 38635.
Ann Benes lives at 2447 S. Greenwood Ave Las Vegas in NY, 55366.
Erica Gates lives at 3141 Farnam Street Omaha in CA, 57640.
Warren Williams lives at 6670 S. Greenwood Ave Hollywood in FL, 37288.
Harry Darrow lives at 3273 Isabella Ave Houston in FL, 97261.
Steve Darrow lives at 8407 Infinite Loop Drive Las Vegas in WA, 90520.

가변형 FlatfileItemWriter Sample

@Bean
@StepScope
public FlatFileItemWriter<Customer> itemWriter(
        @Value("#{jobParameters['outputFile']}") Resource outputFile) {
    return new FlatFileItemWriterBuilder<Customer>()
            .name("customerItemWriter")
            .resource(outputFile)
            .delimited()
            .delimiter(";")
            .names(new String[] {
                    "firstName",
                    "lastName",
                    "address",
                    "city",
                    "state",
                    "zip"
            })
            .build();
}

Output 결과 예시

$ cat ./Chapter09/target/classes/output/delimitedCustomers.txt
Richard;Darrow;5570 Isabella Ave;St. Louis;IL;58540
Warren;Darrow;4686 Mt. Lee Drive;St. Louis;NY;94935
Barack;Donnelly;7844 S. Greenwood Ave;Houston;CA;38635
Ann;Benes;2447 S. Greenwood Ave;Las Vegas;NY;55366
Erica;Gates;3141 Farnam Street;Omaha;CA;57640
Warren;Williams;6670 S. Greenwood Ave;Hollywood;FL;37288
Harry;Darrow;3273 Isabella Ave;Houston;FL;97261
Steve;Darrow;8407 Infinite Loop Drive;Las Vegas;WA;90520