ppb
ppb

Reputation: 2623

Spring Batch read from .txt or .dat file

How I can read .txt or .dat file from Spring Batch. I have data in those file with space or pipe separated so how I can read that data and stored into database.

Upvotes: 0

Views: 8494

Answers (2)

Bug
Bug

Reputation: 483

Here is the final code I implemented and its working .To read from Abc.txt file. filed1 ,filed2 are Person class attributes.

@Bean
public FlatFileItemReader<Person> reader() {

    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    tokenizer.setDelimiter("|");
    tokenizer.setNames(new String[]{"filed1", "filed1"});

    DefaultLineMapper lineMapper = new DefaultLineMapper<Person>();
    lineMapper.setLineTokenizer(tokenizer);


    return new FlatFileItemReaderBuilder<Person>()
        .name("personItemReader")
        .resource(new ClassPathResource("Abc.txt"))
        .lineTokenizer(tokenizer)
        //.delimited()
        //.names(new String[]{"filed1", "filed1"})
        .fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
            setTargetType(Person.class);
        }})
        .build();
}

To write into DB

@Bean
public JdbcBatchItemWriter<Person> writer(@Qualifier("localdbSource") final DataSource dataSource) {
    return new JdbcBatchItemWriterBuilder<Person>()
        .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
        .sql("INSERT INTO tablename (column_name,column_name) VALUES (:filed1, :filed1)")
        .dataSource(dataSource)
        .build();
}

Data source configuration as below

@Bean
public DataSource localdbSource() throws SQLException {
    final SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
    dataSource.setDriver(new oracle.jdbc.driver.OracleDriver());
    dataSource.setUrl("urdburl");
    dataSource.setUsername("username");
    dataSource.setPassword("Password");
    return dataSource;
}

Upvotes: 1

Mahmoud Ben Hassine
Mahmoud Ben Hassine

Reputation: 31600

A text file is a flat file, so you can use the FlatFileItemReader for that. With this reader, you can configure the delimiter to a space or pipe using FlatFileItemReaderBuilder.DelimitedBuilder#delimiter.

Upvotes: 2

Related Questions