Read text file into string array (and write)

前端 未结 5 849
-上瘾入骨i
-上瘾入骨i 2020-12-07 08:44

The ability to read (and write) a text file into and out of a string array is I believe a fairly common requirement. It is also quite useful when starting with a language re

5条回答
  •  情深已故
    2020-12-07 09:33

    You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.

    Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:

    package main
    
    import (
        "os"
        "bufio"
        "bytes"
        "fmt"
    )
    
    // Read a whole file into the memory and store it as array of lines
    func readLines(path string) (lines []string, err os.Error) {
        var (
            file *os.File
            part []byte
            prefix bool
        )
        if file, err = os.Open(path); err != nil {
            return
        }
        reader := bufio.NewReader(file)
        buffer := bytes.NewBuffer(make([]byte, 1024))
        for {
            if part, prefix, err = reader.ReadLine(); err != nil {
                break
            }
            buffer.Write(part)
            if !prefix {
                lines = append(lines, buffer.String())
                buffer.Reset()
            }
        }
        if err == os.EOF {
            err = nil
        }
        return
    }
    
    func main() {
        lines, err := readLines("foo.txt")
        if err != nil {
            fmt.Println("Error: %s\n", err)
            return
        }
        for _, line := range lines {
            fmt.Println(line)
        }
    }
    

    Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create() followed by a loop similar to that one in the example (see main()).

提交回复
热议问题