Scanner类是否一次将整个文件加载到内存中? [英] Does the Scanner class load the entire file into memory at once?

查看:338
本文介绍了Scanner类是否一次将整个文件加载到内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用Scanner类来读取文件,因为它非常方便。

I often use the Scanner class to read files because it is so convenient.

      String inputFileName;
      Scanner fileScanner;

      inputFileName = "input.txt";
      fileScanner = new Scanner (new File(inputFileName));

我的问题是,上述语句是否一次将整个文件加载到内存中?或者对fileScanner进行后续调用,如

My question is, does the above statement load the entire file into memory at once? Or do subsequent calls on the fileScanner like

      fileScanner.nextLine();

从文件中读取(即从外部存储器读取而不是从内存中读取)?我问,因为我担心如果文件太大而无法一次性读入内存会发生什么。谢谢。

read from the file (i.e. from external storage and not from memory)? I ask because I am concerned about what might happen if the file is too huge to be read into memory all at once. Thanks.

推荐答案

如果你阅读了源代码,你可以自己回答这个问题。

If you read the source code you can answer the question yourself.

看起来有问题的Scanner构造函数的实现显示:

It appear that the implementation of the Scanner constructor in question shows:

public Scanner(File source) throws FileNotFoundException {
        this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}

后者包含在阅读器中:

private static Readable makeReadable(ReadableByteChannel source, CharsetDecoder dec) {
    return Channels.newReader(source, dec, -1);
}

并使用缓冲区大小读取

private static final int BUFFER_SIZE = 1024; // change to 1024;

正如你在建筑链的最终构造函数中看到的那样:

As you can see in the final constructor in the construction chain:

private Scanner(Readable source, Pattern pattern) {
        assert source != null : "source should not be null";
        assert pattern != null : "pattern should not be null";
        this.source = source;
        delimPattern = pattern;
        buf = CharBuffer.allocate(BUFFER_SIZE);
        buf.limit(0);
        matcher = delimPattern.matcher(buf);
        matcher.useTransparentBounds(true);
        matcher.useAnchoringBounds(false);
        useLocale(Locale.getDefault(Locale.Category.FORMAT));
    }

因此,扫描仪似乎不会立即读取整个文件。

So, it appears scanner does not read the entire file at once.

这篇关于Scanner类是否一次将整个文件加载到内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆