简体   繁体   中英

How can I write to stdout using FlatFileItemWriter in spring batch?

I have the following writer configured in my beans definition file of a spring batch project :

<bean id="writer" class="org.springframework.batch.item.file.FlatFileItemWriter">
    <property name="resource" value="file:/path/to/somefile"/>
    <property name="lineAggregator">
        <bean class="MyCustomLineAggregator"/>
    </property>
</bean>

Now, instead of writing to /path/to/somefile, I want the output to go to the stdout, reason being that I want to launch this job through the command-line launcher and pipe the output to another unix program.

I tried by setting the resource property to "file:/dev/stdout", but then I get the exception : org.springframework.batch.item.ItemStreamException: Unable to create file: [/dev/stdout]

I tried to see if there was an out of the box resource that could handle this, but I'm a bit clueless on which one could do the job...

Thanks for your help.

EDIT : Below is the solution I came up with, following your advise :

import java.util.List;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;

public class StdoutWriter<T> implements ItemWriter<T> {

LineAggregator<T> lineAggregator;

public void setLineAggregator(LineAggregator<T> lineAggregator) {
    this.lineAggregator = lineAggregator;
}

@Override
public void write(List<? extends T> items) throws Exception {
    for (T item : items) {
        System.out.println(lineAggregator.aggregate(item));
    }
}

}

I don't think there is anything out of the box that does what you are looking for. It is simple enough to create your own ItemWriter that does a simple System.out.println() . You can then use the CompositeItemWriter to tie the two together if you still want the file.

Alternately, you can throw on a custom ItemWriterListener and do the printing there.

There's another hack you can use to write to stdout. Essentially, you can specify /dev/stdout as the output file resource. Be sure to set shouldDeleteIfExists to false and appendAllowed to true within the writer or you'll get runtime errors.

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