org.springframework.batch.item.file.FlatFileItemWriter Java Examples

The following examples show how to use org.springframework.batch.item.file.FlatFileItemWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileItemWriterDemo.java    From SpringAll with MIT License 7 votes vote down vote up
private FlatFileItemWriter<TestData> fileItemWriter() throws Exception {
    FlatFileItemWriter<TestData> writer = new FlatFileItemWriter<>();

    FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file");
    Path path = Paths.get(file.getPath());
    if (!Files.exists(path)) {
        Files.createFile(path);
    }
    writer.setResource(file); // 设置目标文件路径

    // 把读到的每个TestData对象转换为JSON字符串
    LineAggregator<TestData> aggregator = item -> {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(item);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    };

    writer.setLineAggregator(aggregator);
    writer.afterPropertiesSet();
    return writer;
}
 
Example #2
Source File: ConvertNamesJobConfig.java    From spring-batch with MIT License 6 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  BeanWrapperFieldExtractor<Person> fieldExtractor = new BeanWrapperFieldExtractor<>();
  fieldExtractor.setNames(new String[] {"firstName", "lastName"});
  fieldExtractor.afterPropertiesSet();

  DelimitedLineAggregator<Person> lineAggregator = new DelimitedLineAggregator<>();
  lineAggregator.setDelimiter(",");
  lineAggregator.setFieldExtractor(fieldExtractor);

  FlatFileItemWriter<Person> flatFileItemWriter = new FlatFileItemWriter<>();
  flatFileItemWriter.setName("personItemWriter");
  flatFileItemWriter.setResource(new FileSystemResource("target/test-outputs/persons.txt"));
  flatFileItemWriter.setLineAggregator(lineAggregator);

  return flatFileItemWriter;
}
 
Example #3
Source File: CapitalizeNamesJobConfig.java    From spring-batch with MIT License 6 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  BeanWrapperFieldExtractor<Person> fieldExtractor =
      new BeanWrapperFieldExtractor<>();
  fieldExtractor.setNames(new String[] {"firstName", "lastName"});
  fieldExtractor.afterPropertiesSet();

  DelimitedLineAggregator<Person> lineAggregator =
      new DelimitedLineAggregator<>();
  lineAggregator.setDelimiter(",");
  lineAggregator.setFieldExtractor(fieldExtractor);

  FlatFileItemWriter<Person> flatFileItemWriter =
      new FlatFileItemWriter<>();
  flatFileItemWriter.setName("personItemWriter");
  flatFileItemWriter.setResource(
      new FileSystemResource("target/test-outputs/persons.txt"));
  flatFileItemWriter.setLineAggregator(lineAggregator);

  return flatFileItemWriter;
}
 
Example #4
Source File: CapitalizeNamesJobConfig.java    From spring-batch with MIT License 5 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  return new FlatFileItemWriterBuilder<Person>()
      .name("personItemWriter")
      .resource(new FileSystemResource(
          "target/test-outputs/persons.txt"))
      .delimited().delimiter(", ")
      .names(new String[] {"firstName", "lastName"}).build();
}
 
Example #5
Source File: CapitalizeNamesJobConfig.java    From spring-batch with MIT License 5 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  return new FlatFileItemWriterBuilder<Person>()
      .name("personItemWriter")
      .resource(new FileSystemResource(
          "target/test-outputs/persons.txt"))
      .delimited().delimiter(", ")
      .names(new String[] {"firstName", "lastName"}).build();
}
 
Example #6
Source File: CapitalizeNamesJobConfig.java    From spring-batch with MIT License 5 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  return new FlatFileItemWriterBuilder<Person>()
      .name("personItemWriter")
      .resource(new FileSystemResource(
          "target/test-outputs/persons.txt"))
      .delimited().delimiter(", ")
      .names(new String[] {"firstName", "lastName"}).build();
}
 
Example #7
Source File: HelloWorldJobConfig.java    From spring-batch with MIT License 5 votes vote down vote up
@Bean
public FlatFileItemWriter<String> writer() {
  return new FlatFileItemWriterBuilder<String>()
      .name("greetingItemWriter")
      .resource(new FileSystemResource(
          "target/test-outputs/greetings.txt"))
      .lineAggregator(new PassThroughLineAggregator<>()).build();
}
 
Example #8
Source File: ItemWriterConfigure.java    From SpringAll with MIT License 5 votes vote down vote up
@Bean
public FlatFileItemWriter<TestData> fileItemWriter() throws Exception {
    FlatFileItemWriter<TestData> writer = new FlatFileItemWriter<>();

    FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file");
    Path path = Paths.get(file.getPath());
    if (!Files.exists(path)) {
        Files.createFile(path);
    }

    writer.setResource(file); // 设置目标文件路径

    // 把读到的每个TestData对象转换为字符串
    LineAggregator<TestData> aggregator = item -> {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(item);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    };

    writer.setLineAggregator(aggregator);
    writer.afterPropertiesSet();
    return writer;
}
 
Example #9
Source File: ConvertNamesJobConfig.java    From spring-batch with MIT License 4 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  return new FlatFileItemWriterBuilder<Person>().name("personItemWriter")
      .resource(new FileSystemResource("target/test-outputs/persons.txt"))
      .lineAggregator(new PassThroughLineAggregator<>()).build();
}
 
Example #10
Source File: CapitalizeNamesJobConfig.java    From spring-batch with MIT License 4 votes vote down vote up
@Bean
public FlatFileItemWriter<Person> itemWriter() {
  return new FlatFileItemWriterBuilder<Person>()
      .name("personItemWriter")
      .resource(new FileSystemResource(
          "target/test-outputs/persons.txt"))
      .delimited().delimiter(", ")
      .names(new String[] {"firstName", "lastName"}).build();
}
 
Example #11
Source File: FlatFileItemWriterAutoConfiguration.java    From spring-cloud-task with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.batch.job.flatfilewriter", name = "name")
public FlatFileItemWriter<Map<Object, Object>> itemWriter() {

	if (this.properties.isDelimited() && this.properties.isFormatted()) {
		throw new IllegalStateException(
				"An output file must be either delimited or formatted or a custom "
						+ "LineAggregator must be provided. Your current configuration specifies both delimited and formatted");
	}
	else if ((this.properties.isFormatted() || this.properties.isDelimited())
			&& this.lineAggregator != null) {
		throw new IllegalStateException("A LineAggregator must be configured if the "
				+ "output is not formatted or delimited");
	}

	FlatFileItemWriterBuilder<Map<Object, Object>> builder = new FlatFileItemWriterBuilder<Map<Object, Object>>()
			.name(this.properties.getName()).resource(this.properties.getResource())
			.append(this.properties.isAppend())
			.encoding(this.properties.getEncoding())
			.forceSync(this.properties.isForceSync())
			.lineSeparator(this.properties.getLineSeparator())
			.saveState(this.properties.isSaveState())
			.shouldDeleteIfEmpty(this.properties.isShouldDeleteIfEmpty())
			.shouldDeleteIfExists(this.properties.isShouldDeleteIfExists())
			.transactional(this.properties.isTransactional())
			.headerCallback(this.headerCallback).footerCallback(this.footerCallback);

	if (this.properties.isDelimited()) {
		FlatFileItemWriterBuilder.DelimitedBuilder<Map<Object, Object>> delimitedBuilder = builder
				.delimited().delimiter(this.properties.getDelimiter());

		if (this.fieldExtractor != null) {
			delimitedBuilder.fieldExtractor(this.fieldExtractor);
		}
		else {
			delimitedBuilder.fieldExtractor(
					new MapFieldExtractor(this.properties.getNames()));
		}
	}
	else if (this.properties.isFormatted()) {
		FlatFileItemWriterBuilder.FormattedBuilder<Map<Object, Object>> formattedBuilder = builder
				.formatted().format(this.properties.getFormat())
				.locale(this.properties.getLocale())
				.maximumLength(this.properties.getMaximumLength())
				.minimumLength(this.properties.getMinimumLength());

		if (this.fieldExtractor != null) {
			formattedBuilder.fieldExtractor(this.fieldExtractor);
		}
		else {
			formattedBuilder.fieldExtractor(
					new MapFieldExtractor(this.properties.getNames()));
		}
	}
	else if (this.lineAggregator != null) {
		builder.lineAggregator(this.lineAggregator);
	}

	return builder.build();
}
 
Example #12
Source File: FlatFileItemWriterAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 4 votes vote down vote up
@Test
public void testDelimitedFileGeneration() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withUserConfiguration(DelimitedJobConfiguration.class)
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							BatchAutoConfiguration.class,
							SingleStepJobAutoConfiguration.class,
							FlatFileItemWriterAutoConfiguration.class))
			.withPropertyValues("spring.batch.job.jobName=job",
					"spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5",
					"spring.batch.job.flatfilewriter.name=fooWriter",
					String.format(
							"spring.batch.job.flatfilewriter.resource=file://%s",
							this.outputFile.getAbsolutePath()),
					"spring.batch.job.flatfilewriter.encoding=UTF-16",
					"spring.batch.job.flatfilewriter.saveState=false",
					"spring.batch.job.flatfilewriter.shouldDeleteIfEmpty=true",
					"spring.batch.job.flatfilewriter.delimited=true",
					"spring.batch.job.flatfilewriter.names=item",
					"spring.batch.job.flatfilewriter.append=true",
					"spring.batch.job.flatfilewriter.forceSync=true",
					"spring.batch.job.flatfilewriter.shouldDeleteIfExists=false",
					"spring.batch.job.flatfilewriter.transactional=false");

	applicationContextRunner.run((context) -> {
		JobLauncher jobLauncher = context.getBean(JobLauncher.class);

		Job job = context.getBean(Job.class);

		JobExecution jobExecution = jobLauncher.run(job, new JobParameters());

		JobExplorer jobExplorer = context.getBean(JobExplorer.class);

		while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) {
			Thread.sleep(1000);
		}

		FlatFileItemWriter writer = context.getBean(FlatFileItemWriter.class);

		AssertFile.assertLineCount(3, this.outputFile);
		AssertFile.assertFileEquals(new ClassPathResource("writerTestUTF16.txt"),
				new FileSystemResource(this.outputFile));

		assertThat((Boolean) ReflectionTestUtils.getField(writer, "saveState"))
				.isFalse();
		assertThat((Boolean) ReflectionTestUtils.getField(writer, "append")).isTrue();
		assertThat((Boolean) ReflectionTestUtils.getField(writer, "forceSync"))
				.isTrue();
		assertThat((Boolean) ReflectionTestUtils.getField(writer,
				"shouldDeleteIfExists")).isFalse();
		assertThat((Boolean) ReflectionTestUtils.getField(writer, "transactional"))
				.isFalse();
	});
}