java文件总行数,Java中InputStream(或CsvMapper)中的总行数

How can I get the number of lines(rows) from an InputStream or from a CsvMapper without looping through and counting them?

Below I have an InputStream created from a CSV file.

InputStream content = (... from a resource ...);

CsvMapper mapper = new CsvMapper();

mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);

MappingIterator it = mapper

.reader(Object[].class)

.readValues(content);

Is it possible to do something like

int totalRows = mapper.getTotalRows();

I would like to use this number in the loop to update progress.

while (it.hasNextValue()){

//do stuff here

updateProgressHere(currentRow, totalRows);

}

Obviously, I can loop through and count them once. Then loop through again and process them while updating progress. This is inefficient and slow as some of these InputStreams are huge.

解决方案

Unless you know the row count ahead of time, it is not possible without looping. You have to read that file in its entirety to know how many lines are in it, and neither InputStream nor CsvMapper have a means of reading ahead and abstracting that for you (they are both stream oriented interfaces).

None of the interfaces that ObjectReader can operate on support querying the underlying file size (if it's a file) or number of bytes read so far.

One possible option is to create your own custom InputStream that also provides methods for grabbing the total size and number of bytes read so far, e.g. if it is reading from a file, it can expose the underlying File.length() and also track the number of bytes read. This may not be entirely accurate, especially if Jackson buffers far ahead, but it could get you something at least.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值