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

如何使用Scanner让Java读取非常大的文件?,java,memory,large-files,java.util.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

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

    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");
}
}
它可以很好地处理中小型文件(包含10000到20000行数据) 但是,它无法处理包含50万行的文件。我没有出错(至少没有看到任何人)。那么到底发生了什么?我该怎么做才能准备这么大的文件

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

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


更新01

以下是输出

开始

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

审判结束

结束


如果你没有得到一个错误,它很可能只是需要很长时间。磁盘是否仍处于活动状态?您对控制台输出做了什么-它停止了吗?你说它“不起作用”,但你没有说它的实际行为。你在看什么

内存不应该是一个问题,因为您实际上并没有对这些行执行任何操作—只是计算它们并将它们写入控制台


代码中有一个问题-您正在检查
scanner
是否为null,但不可能为null,因为您使用的是构造函数调用返回的引用。您试图处理的是什么情况?

最好使用带文件读取器的BufferedReader

我认为这需要很长时间,但输出已经显示了上一次打印语句的结果,这意味着它已完成工作。这个类应该是我的程序的一部分,它需要处理每一行,然后把它放在一个新的文件中。你知道怎么做吗?你是最棒的!:)BufferedReader解决了这个问题!非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。非常感谢。