Java使用CSVReader有更快方法吗?大CSV分段读取skip过慢如何优化
解决方案
最优方案:全量缓存采样数据
你的总采样点仅有13.5万,每个int仅占4字节,全量加载到内存仅需约500KB,完全不会占用过多内存,是性能最高的实现方式:
- 提前在页面/应用初始化阶段,一次性读取整个CSV文件的所有采样值,存入全局
List<Integer> allSamples - 切换分段时直接从全量列表中截取对应区间即可,无需重复读取文件
示例改造代码:
// 初始化阶段执行一次即可 private List<Integer> allSamples = new ArrayList<>(); private void initAllSamples() { try (CSVReader reader = new CSVReader(new FileReader(new File(patty)))) { Iterator<String[]> it = reader.iterator(); while (it.hasNext()) { allSamples.add(Integer.parseInt(it.next()[0])); } } catch (Exception e) { e.printStackTrace(); } } // 切换分段的方法改造 public void updateSign(int segmento) { Log.d("segmento", Integer.toString(segmento)); int maxSegment = (int) Math.ceil((float) TOTAL / normaLen); if (segmento <=0 || segmento > maxSegment) { return; } int start = (segmento -1) * normaLen; int end = Math.min(segmento * normaLen, TOTAL); // 截取对应分段数据 List<Integer> sign = new ArrayList<>(allSamples.subList(start, end)); // 处理末尾段标记 avanti.setValue(end < TOTAL); liveSign.setValue(sign); }
次优方案:预存分段偏移索引
如果后续采样量扩充到百万级以上,不适合全量缓存,可以预先生成分段的文件字节偏移索引,避免逐行skip:
- 第一次读取文件时,遍历每一行,记录每
normaLen行对应的文件指针偏移量,存入long[] segmentOffsets数组 - 后续切换分段时,直接用
RandomAccessFile跳转到对应偏移位置,再创建CSVReader读取当前段的5000行即可,跳转耗时为O(1)
实现注意:CSVReader默认带缓冲,直接用FileReader无法准确控制指针,必须基于RandomAccessFile定位后再包装为Reader传入。
原有方案的性能问题说明
OpenCSV的CSVReader.skip()方法底层确实是通过循环调用readNext()逐行读取并丢弃实现的,跳转N行就需要读取N行,当你跳转末尾段时需要读取十几万行,因此耗时极高。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

