我正在尝试使用beanio创建一个固定长度的文件输出。我不想写物理文件,相反,我想把内容写到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
}
这里创建的文件file.txt中没有内容,大小为0kb。
我可以用下面的方法写文件,但由于我不想在物理位置写文件,我想把内容写到outputStream中,然后用另一种方法,它可以转换成文件
//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);
为什么在第一种方法中创建的文件大小为0kb?
您似乎没有向OutputstreamWriter
写入足够的数据,无法将一些数据推送到底层ByteArrayOutputStream
。这里有两个选项。
- 手动刷新
writer
对象,然后关闭它。这将把数据写入outputStream
。我不建议使用这种方法,因为在手动刷新和关闭writer
之前,如果出现任何异常,可能不会刷新或关闭writer
- 为
writer
使用try-with-resource
块,该块应负责关闭writer
并最终将数据刷新到outputStream
这应该可以做到:
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
}