Does the Scanner class load the entire file into memory at once?

前端 未结 4 593
轮回少年
轮回少年 2020-12-07 02:15

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

      String inputFileName;
      Scanner fileScanner;

      inputFileName = \"inp         


        
4条回答
  •  失恋的感觉
    2020-12-07 02:56

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

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

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

    Latter this is wrapped into a Reader:

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

    And it is read using a buffer size

    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.

提交回复
热议问题