3

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

    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 行数据)但是它无法处理包含 500,000 行的文件。我没有收到错误(至少没有看到任何人)。那么发生了什么?我应该在这里做什么才能准备这么大的文件?

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

请任何人都可以告诉我我应该在这里做什么?


更新01

以下是输出

开始

java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,] [小数分隔符=.][正前缀=][负前缀=\Q-\E][正后缀=][负后缀=][NaN字符串=\Q�\E][无穷大字符串=\Q∞\E ]

Try Bluck 结束

结尾

4

2 回答 2

5

使用 FileReader 更好地选择 BufferedReader

于 2010-02-11T07:17:27.130 回答
1

如果您没有收到错误,则很可能需要很长时间。磁盘是否仍处于活动状态?你在用控制台输出做什么 - 它停止了吗?你说它“无法工作”,但你还没有说它实际上是如何表现的。你在看什么?

内存应该不是问题,因为您实际上并没有对这些行做任何事情 - 只是计算它们并将它们写入控制台。

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

于 2010-02-11T07:05:51.657 回答