Search code examples
springspring-batch

LineSeparator after headerCallback.writeHeader in AbstractFileItemWriter in Spring Batch


A lineseperator is always appended after header is writte in AbstractFileItemWriter. As you can see in the following method outputState.write(this.lineSeparator); is called after header is written.

private void doOpen(ExecutionContext executionContext) throws ItemStreamException {
        AbstractFileItemWriter<T>.OutputState outputState = this.getOutputState();
        if (executionContext.containsKey(this.getExecutionContextKey("current.count"))) {
            outputState.restoreFrom(executionContext);
        }

        try {
            outputState.initializeBufferedWriter();
        } catch (IOException var5) {
            throw new ItemStreamException("Failed to initialize writer", var5);
        }

        if (outputState.lastMarkedByteOffsetPosition == 0L && !outputState.appending && this.headerCallback != null) {
            try {
                this.headerCallback.writeHeader(outputState.outputBufferedWriter);
                outputState.write(this.lineSeparator);
            } catch (IOException var4) {
                throw new ItemStreamException("Could not write headers.  The file may be corrupt.", var4);
            }
        }

    }

How can we write everything in a single line to a file? I wrote a new writer extending AbstractFileItemWriter and implemented the doWrite method. So everything is written in a single line except the header.


Solution

  • I achieved the above in following way. Unfortunately 'doOpen' in AbstractFileItemWriter can't be overriden. So I override 'open' and called the super. Then I wrote an interface for my header callback and called it in overriden 'open' method without linesepearator.

    @Override
        public void open(ExecutionContext executionContext) throws ItemStreamException {
            super.open(executionContext);
            AbstractFileItemWriter<EodFileGroup>.OutputState outputState = this.getOutputState();
    
            if (this.groupIemHeaderCallback != null) {
                try {
                    outputState.write(this.groupIemHeaderCallback.getHeader());
                } catch (IOException var4) {
                    throw new ItemStreamException("Could not write headers.  The file may be corrupt.", var4);
                }
            }
        }