Scanner类是否一次将整个文件加载到内存中?

Cod*_*lue 5 java java.util.scanner

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

      String inputFileName;
      Scanner fileScanner;

      inputFileName = "input.txt";
      fileScanner = new Scanner (new File(inputFileName));
Run Code Online (Sandbox Code Playgroud)

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

      fileScanner.nextLine();
Run Code Online (Sandbox Code Playgroud)

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

Edw*_*rzo 15

如果您阅读源代码,您可以自己回答问题.

似乎有问题的Scanner构造函数的实现显示:

public Scanner(File source) throws FileNotFoundException {
        this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
Run Code Online (Sandbox Code Playgroud)

后者将其包装到Reader中:

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

并使用缓冲区大小读取它

private static final int BUFFER_SIZE = 1024; // change to 1024;
Run Code Online (Sandbox Code Playgroud)

正如您在构造链的最终构造函数中所看到的:

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));
    }
Run Code Online (Sandbox Code Playgroud)

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

  • @Aidanc有什么问题? (4认同)