简体   繁体   中英

Spring batch, how do I write simple strings into a file?

I'm new to spring batch and so far I've studied how to take a list of Objects as input from csv,xml,json files or DBs and write down those same Object in external files or DBs. However I just realized that I don't know how to output simple strings, for example I've made this simple Processor:

public class ProductProcessorObjToStr implements ItemProcessor<Product,String> {
    @Override
    public String process(Product product) throws Exception {
        return product.getProductName();
    }
}

So that I get a simple list of names but I have no idea how to create the correct item writer. I've studied theese kinds of writers where I map the various Object fields:

@Bean
@StepScope
public FlatFileItemWriter flatFileItemWriter(@Value("#{jobParameters['outputFile']}") FileSystemResource outputFile){
        FlatFileItemWriter writer = new FlatFileItemWriter<Product>();
        writer.setResource(outputFile);
        writer.setLineAggregator(new DelimitedLineAggregator(){
            {
                setDelimiter("|");
                setFieldExtractor(new BeanWrapperFieldExtractor(){
                    {
                        setNames(new String[] 
                        {"productID","productName","productDesc","price","unit"});
                    }
                });
            }
        });
        writer.setHeaderCallback(new FlatFileHeaderCallback() {
            @Override
            public void writeHeader(Writer writer) throws IOException {
                writer.write("productID,productName,ProductDesc,price,unit");
            }
        });
        writer.setFooterCallback(new FlatFileFooterCallback() {
            @Override
            public void writeFooter(Writer writer) throws IOException {
                //scrivo il footer
                writer.write("****** File created at  " + new SimpleDateFormat().format(new 
                Date()) + " ******");
            }
        });
        return writer;
    }

Which writer do I use for strings and how do I create it? Thank you in advance for your suggestions. Have a nice day.

for this case I think java.io.PrintWriter should do it and you can use method printLn() to print your string in a line if you want this, and if you want to write a object and then read it and load it in your app use java.io.ObjectOutputStream to write your object then use java.io.ObjectInputStream to read it and load it to an instance of your object note that you should implement java.io.Serializable to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM