'Beanio - How to write to stream object
I am trying to create a fixed length file output using beanio. I don't want to write the physical file, instead I want to write content to an OutputStream.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
StreamFactory factory = StreamFactory.newInstance();
StreamBuilder builder = new StreamBuilder("sb")
.format("fixedlength")
.parser(new FixedLengthParserBuilder())
.addRecord(Team.class);
factory.define(builder);
OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
BeanWriter bw = sf.createWriter("sb", writer);
bw.write(teamVO) // teamVO has some value.
try(OutputStream os = new FileOutputStream("file.txt")){
outputStream.writeTo(os); //Doing this only to check outputStream has some value
}
Here the file created, file.txt has no content in it, It is of size 0 kb.
I am able to write the file in the following method, but as I don't want to write the file in physical location, I thought of writing the contents in to a outputStream and then later in a different method, it can be converted in to a file
//This is working and creates file successfully
StreamFactory factory = StreamFactory.newInstance();
StreamBuilder builder = new StreamBuilder("sb")
.format("fixedlength")
.parser(new FixedLengthParserBuilder())
.addRecord(Team.class)
factory.define(builder);
BeanWriter bw = factory.createWriter("sb", new File("file.txt"));
bw.write(teamVO);
Why in the first approach the file is created with size 0 kb?
Solution 1:[1]
It looks like you haven't written enough data to the OutputstreamWriter for it to push some data to the underlying ByteArrayOutputStream. You have 2 options here.
- Flush the
writerobject manually and then close it. This will then write the data to theoutputStream. I would not recommend this approach because thewritermay not be flushed or closed should there be any Exception before you could manually flush and close thewriter. - Use a
try-with-resourceblock for thewriterwhich should take care of closing thewriterand ultimately flushing the data to theoutputStream
This should do the trick:
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (final OutputStreamWriter writer = new OutputStreamWriter(outputStream) ) {
final BeanWriter bw = factory.createWriter("sb", writer);
final Team teamVO = new Team();
teamVO.setName("TESTING");
bw.write(teamVO); // teamVO has some value.
}
try (OutputStream os = new FileOutputStream("file.txt") ) {
outputStream.writeTo(os); // Doing this only to check outputStream has some value
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nicoschl |
