java - 如何让 Java 使用 Scanner 读取非常大的文件?

标签 java memory large-files java.util.scanner

我正在使用从网上复制的以下基本函数来读取文本文件

    public void read ()
{
    File file = new File("/Users/MAK/Desktop/data.txt");
    System.out.println("Start");
    try
    {
        //
        // Create a new Scanner object which will read the data from the
        // file passed in. To check if there are more line to read from it
        // we check by calling the scanner.hasNextLine() method. We then
        // read line one by one till all line is read.
        //
        Scanner scanner = new Scanner(file);
        int lineCount = 0;
        if (scanner == null)
        {
            System.out.println("Null File");
        }
        else
        {
            System.out.println(scanner.toString());
        }
        while (scanner.hasNextLine())
        {
            String line = scanner.nextLine();

            System.out.println("Line " + lineCount +" contain : " + line);
            lineCount++;
        }
        System.out.println("End of Try Bluck");
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
        System.out.println("Exception Bluck");
    }
    System.out.println("End");
}
}

它适用于中小型文件(包含 10 到 20,000 行数据) 但是,它无法处理包含 50 万行的文件。我没有收到错误(至少没有看到任何人)。那么发生了什么?我应该在这里做什么才能准备好这么大的文件?

注意:我已经在运行 Windows Server 2008 和 4 GB 内存的测试机器上增加了 2 GB 的堆。但这并没有多大帮助!

请谁能告诉我我应该在这里做什么?


更新 01

下面是输出

Start

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]

End of Try Bluck

End

最佳答案

最好使用带有 FileReader 的 BufferedReader

关于java - 如何让 Java 使用 Scanner 读取非常大的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2242782/

相关文章:

javascript - 使用 java 或 google script 读取单元格值

java - 向 ibm-mq 发送消息时出现 UnSatisfied Link 异常

java - 小于 ObjectOutputStream 基元的基元数组

mysql - 如何将大型 (14 GB) MySQL 转储文件导入新的 MySQL 数据库?

linux - 试图从 git repo 中删除一个大文件夹但花费的时间太长

java - List<LineItem> 类型的方法 sort(LineItem.FullLineItemComparator) 未定义

java - 老程序员希望使用 subversion assembla

haskell - Cabal安装标准内存不足

c++ - 您将如何使用二维来处理一维内存?

python - Flask中的大文件上传