AssenKhan
AssenKhan

Reputation: 566

Spring Batch - Custom Item Writer not Writing On file

at the End of the Batch File Created with the Name ReportDetail, But nothing is there in this file

public class ReportWriter implements ItemWriter<Record>,Closeable {

    private PrintWriter writer = null;

    public ReportWriter() {
        OutputStream out;
        try {
            out = new FileOutputStream("ReportDetail.txt");
        } catch (FileNotFoundException e) {
            System.out.println("Exception e" + e);
            out = System.out;
        }
        try {
            this.writer = new PrintWriter(out);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println(""+e);
        }
    }

    @Override
    public void write(final List<? extends Record> items) throws Exception {
        for (Record item : items) {
            System.out.println("item.getCode()"); // this Prints the Code
            writer.println(item.getCode()); // Not Working
        }
    }

    @PreDestroy
    @Override
    public void close() throws IOException {
        writer.close();
    }
}

Upvotes: 1

Views: 3302

Answers (1)

Michael Minella
Michael Minella

Reputation: 21453

A couple things here:

  1. Why not use the FlatFileItemWriter? I don't see anything you're doing here that can't be done with it.
  2. Don't use Closable for an ItemWriter. Spring Batch has a lifecycle for opening and closing resources. It's the ItemStream interface. You can read more about it in the documentation here: https://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/item/ItemStream.html
  3. Your PrintWriter is not configured to flush automatically (it's false by default). You need to either enable that (so that your writer flushes after each line) or explicitly call writer.flush() at the end of the write method.

Upvotes: 2

Related Questions