728x90
반응형
source 는 Github 에 있습니다.
목차는 spring batch 목차 에 있습니다.
[spring batch 2편] FlatFileItemWriter Fixed length format 정리 (Header, Footer 사용)
- 파일을 쓸 때, Fixed length 와 Formatter 를 조합하는 예제에 대해서 정리했습니다.
- DTO to FixedLength format 으로 변환해서 파일을 쓰는 예제입니다. 파일을 쓸 때, Java 의 Formatter 를 사용할 수 있습니다.
Source
- 아래 예제에서 formatted() 옵션을 주면 Java 의 Formatter 를 사용할 수 있습니다.
- 자바의 Formatter 는 링크 를 참고하시면 됩니다.
- Formatter 를 이용한다면 왼쪽 정렬, 오른쪽 정렬, 값이 비어있다면 space, '0' 으로 채우는 등의 작업이 가능합니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// WRITER SOURCE | |
@Bean | |
@StepScope // step 기간동안 빈 lifecycle 관리. | |
public FlatFileItemWriter<FlatFileExampleInfo.Base> flatFileExampleWriter(@Value("#{jobParameters[path]}") String path) { | |
if (StringUtils.isEmpty(path)) { | |
throw new IllegalArgumentException("path is null"); | |
} | |
return new FlatFileItemWriterBuilder() | |
.name("flatFileExampleWriter") | |
.encoding(ENCODING) | |
.headerCallback(getHeaderCallBack()) | |
.footerCallback(getFooterCallback()) | |
.resource(new FileSystemResource(path)) | |
.formatted() // 자바의 formatter 를 적용합니다. | |
.format(FlatFileExampleInfo.Base.getFormat()) // 사용되는 format template 입니다. | |
.names(FlatFileExampleInfo.Base.getNames()) | |
.build(); | |
} | |
// TEST SOURCE | |
@SqlGroup( | |
{ | |
@Sql(scripts = "/sql/FLAT_FILE_EXAMPLE_BEFORE_TEST_SQL.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD), | |
@Sql(scripts = "/sql/FLAT_FILE_EXAMPLE_AFTER_TEST_SQL.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) | |
} | |
) | |
@Test | |
public void DB_읽어서_FLAT_FILE_쓰기_테스트() throws Exception { | |
// when | |
JobParameters jobParameters = new JobParametersBuilder() | |
.addString("dummy", "testData123123") | |
.addString("path", PATH) | |
.toJobParameters(); | |
JobExecution jobExecution = jobLauncherTestUtils.launchJob(jobParameters); | |
// then | |
Assertions.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED); | |
Assertions.assertEquals(jobExecution.getExitStatus(), ExitStatus.COMPLETED); | |
int fileLineCount = FileUtils.getFileLineCount(new File(PATH)); | |
Assertions.assertEquals(4, fileLineCount); | |
} | |
// OUTPUT FILE | |
================FIRST_LINE================ | |
00001 TEST_NAME 010 | |
00002 TEST_NAME2020 | |
================END_LINE================ |
Reference
'Spring > batch' 카테고리의 다른 글
[spring batch 1편] spring batch processor, Writer 에서 sequence 를 mybatis 를 통해 여러 번 가져왔을 때, 같은 값이 나오는 경우 (0) | 2022.08.10 |
---|---|
QuerydslPagingItemReader 병렬 처리 정리 (0) | 2021.09.29 |
spring batch partitioner 정리 (2) | 2021.08.18 |
spring batch multi datasource, jpa, transactionManager 정리 (0) | 2021.07.18 |
spring-batch commit interval 이란? (0) | 2021.07.09 |
댓글