问题
Spring-Batch provides the class FixedLengthTokenizer which makes it easy to read different offsets of a single line into the fileds of an object. Whereby the content of each field is extracted from certain ranges with fixed length:
FixedLengthTokenizer tokenizer = new FixedLengthTokenizer();
String[] names = {"A", "B", "C", "D"};
tokenizer.setNames(names);
Range[] ranges = {new Range(1, 4), new Range(5, 12), new Range(13, 14), new Range(15, 15)};
tokenizer.setColumns(ranges);
I want to do the exact oposite. I want to write an Object into a flat file whereby the different fields should be written into the file with fixed lengths. Spring-Batch provides the interface org.springframework.batch.item.file.transform.LineAggregator for mapping lines to objects. But I'm wondering why there is no FixedLengthLineAggregator for doing that?
What's the right way in Spring-Batch to write objects to lines whereby the fields have a fixed length?
回答1:
As @canillas noted in their comment, the way to manage this would be via Spring Batch's FormatterLineAggregator. Using the format capabilities of String.format can allow you to generate fixed length records in a way that is standard across the JVM and framework independent.
来源:https://stackoverflow.com/questions/47325636/spring-batch-writing-objects-to-lines-with-fixed-length