Reading huge line of string from text file

前端 未结 6 2046
南旧
南旧 2020-12-06 15:27

I have a large text file but doesn\'t have any line break. It just contains a long String (1 huge line of String with all ASCII characters), but so far anything works just f

6条回答
  •  情深已故
    2020-12-06 16:17

    A single String can be only 2 billion characters long and will use 2 byte per character, so if you could read a 5 GB line it would use 10 GB of memory.

    I suggest you read the text in blocks.

    Reader reader = new FileReader("input.txt");
    try {
        char[] chars = new char[8192];
        for(int len; (len = reader.read(chars)) > 0;) {
            // process chars.
        }
    } finally {
        reader.close();
    }
    

    This will use about 16 KB regardless of the size of the file.

提交回复
热议问题