Create a io.Reader from a local file

后端 未结 4 1448
悲哀的现实
悲哀的现实 2021-01-31 00:54

I would like to open a local file, and return a io.Reader. The reason is that I need to feed a io.Reader to a library I am using, like:



        
相关标签:
4条回答
  • 2021-01-31 01:22

    Use os.Open():

    func Open(name string) (file *File, err error)

    Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

    The returned value of type *os.File implements the io.Reader interface.

    0 讨论(0)
  • 2021-01-31 01:35

    os.Open returns an io.Reader

    http://play.golang.org/p/BskGT09kxL

    package main
    
    import (
        "fmt"
        "io"
        "os"
    )
    
    var _ io.Reader = (*os.File)(nil)
    
    func main() {
        fmt.Println("Hello, playground")
    }
    
    0 讨论(0)
  • The type *os.File implements the io.Reader interface, so you can return the file as a Reader. But I recommend you to use the bufio package if you have intentions of read big files, something like this:

    file, err := os.Open("path/file.ext")
    // if err != nil { ... }
    
    return bufio.NewReader(file)
    
    0 讨论(0)
  • 2021-01-31 01:49

    Here is an example where we open a text file and create an io.Reader from the returned *os.File instance f

    package main
    
    import (
        "io"
        "os"
    )
    
    func main() {
        f, err := os.Open("somefile.txt")
        if err != nil {
            panic(err)
        }
        defer f.Close()
    
        var r io.Reader
        r = f
    }
    
    0 讨论(0)
提交回复
热议问题