Package bufio
Table of Contents
Read a file line by line howto
reader.ReadLine()exclude the end-of-line bytes, such as\nand\r.reader.ReadString('\n')will not exclude the end-of-line bytes.- Using
scanner.Scan()followed byscanner.Text()would also be possible.
reader.ReadString('\n')isn't fully equivalent toReadLinebecauseReadStringis unable to handle the case when the last line of a file does not end with the newline character.
The upshot:
reader.ReadString('\n')- If you don't mind that the line could be very long (i.e. use a lot of RAM)
- It keeps the
\nat the end of the string returned.
reader.ReadLine()- If you care about limiting RAM consumption
- If you don't mind the extra work of handling the case where the line is greater than the reader's buffer size.
- For
reader, thedefaultBufSizeis4096bytes.
scanner.Scan(); scanner.Text()- It does not handle long lines. (Just returns
ErrTooLong) - For
scanner, theMaxScanTokenSizeis64 * 1024bytes.
- It does not handle long lines. (Just returns