本文介绍了使用 Apache Commons lineIterator 时出现 OutOfMemory 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Apache Commons FileUtils.lineIterator 逐行迭代一个 1.2GB 的文件.但是,一旦 LineIterator 调用 hasNext(),我就会得到一个 java.lang.OutOfMemoryError: Java heap space.我已经为java堆分配了1G.

I'm trying to iterate line-by-line a 1.2GB file using Apache Commons FileUtils.lineIterator. However, as soon as a LineIterator calls hasNext() I get a java.lang.OutOfMemoryError: Java heap space. I've already allocated 1G to the java heap.

我在这里做错了什么?在阅读了一些文档后,LineIterator 是不是应该从文件系统中读取文件而不是将其加载到内存中?

What am I doing wrong in here? After reading some docs, isn't LineIterator supposed to be reading the file from the file system and not loading it into memory?

注意代码在 Scala 中:

Note the code is in Scala:

  val file = new java.io.File("data_export.dat")
  val it = org.apache.commons.io.FileUtils.lineIterator(file, "UTF-8")
  var successCount = 0L
  var totalCount = 0L
  try {
    while ( {
      it.hasNext()
    }) {
      try {
        val legacy = parse[LegacyEvent](it.nextLine())
        BehaviorEvent(legacy)
        successCount += 1L
      } catch {
        case e: Exception => println("Parse error")
      }
      totalCount += 1
    }
  } finally {
    it.close()
  }

感谢您的帮助!

推荐答案

代码看起来不错.可能它没有在文件中找到一行的结尾,而是将大于 1Gb 的很长的一行读取到内存中.

The code looks good. Probably it does not find an end of a line in the file and reads a very long line which is larger than 1Gb into memory.

在 Unix 中试试 wc -l 看看你得到了多少行.

Try wc -l in Unix and see how many lines you get.

这篇关于使用 Apache Commons lineIterator 时出现 OutOfMemory 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:33