Create a io.Reader from a local file

Go

Go Problem Overview


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:

func read(r io.Reader) (results []string) {

}

Go Solutions


Solution 1 - Go

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")
}

Solution 2 - Go

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.

Solution 3 - Go

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)

Solution 4 - Go

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXi 张熹View Question on Stackoverflow
Solution 1 - GofabrizioMView Answer on Stackoverflow
Solution 2 - GoANisusView Answer on Stackoverflow
Solution 3 - GoYandry PozoView Answer on Stackoverflow
Solution 4 - GospacetherView Answer on Stackoverflow