读文件
- 方式一:利用
ioutil.ReadFile
直接从文件读取到[]byte
func Read(filpath string)(string){
f,err := ioutil.ReadFile(filepath)
if err != nil{
fmt.Println("err:",err)
return
}
return string(f)
}
- 方式二:先从文件读取到file中,再从file读取到buf中,buf在追加到最终的
[]byte
func read(filepath string)(string){
f,err := os.Open(filepath)
if err != nil{
fmt.Println("err:",err)
return
}
defer f.Close()
var chunk []byte
buf := make([]byte,1024)
for{
n,err := f.Read(buf)
if n == 0 || err != io.EOF{
break
}
chunk = append(chunk,buf[:n]...)
}
return chunk
}
- 方式三:先从文件中读到file中,再利用
ioutil
将file直接读到[]byte
func Read(filepath string)(string){
f,err := os.Open(filepath)
if err != nil{
fmt.Println("err:",err)
return
}
defer f.Close()
fd,err = ioutil.ReadAll(f)
if err != nil{
fmt.Println("err:",err)
return
}
return string(fd)
}
- 行读取
func Read(filepath string) (string){
f,err := os.Open(filepath)
if err != nil{
fmt.Println("err:"err)
}
defer f.Close()
var chunk []byte
rd = bufio.NewReader(f)
for {
line,err := rd.ReadString('\n')
if err != nil || io.EOF == err{
break
}
chunk = append(chunk,line...)
}
return chunk
}
- 一次性加载到内存
func Read(filepath string)(string){
file,err := os.Open(filepath)
if err!=nil{
fmt.Println("err:"err)
return
}
defer f.Close()
fileInfo,err := file.Stat()
if err!=nil{
fmt.Println("err:"err)
return
}
buf := make([]byte,fileInfo.Size())
_,err = file.Read()
if err != nil{
fmt.Println("err:"err)
return
}
return string(buf)
}