1.使用os包读取全部文件:
func osReadFile(fileName string) ([]byte , error) {
return os.ReadFile(fileName)
}
2.使用os包按照切片分片读取:
func osRead(fileName string) ([]byte , error) {
file , err := os.Open(fileName)
if err != nil {
return []byte{} , err
}
defer file.Close()
res := []byte{}
tmp := make([]byte,1024*4)
for {
n , err := file.Read(tmp)
if err != nil && err != io.EOF{
return []byte{} , err
}
res = append(res , tmp[:n]...)
if err == io.EOF {
break
}
}
return res , nil
}
3.使用ioutil包读取全部文件:
func ioutilReadAll(fileName string) ([]byte , error) {
file , err := os.Open(fileName)
if err != nil {
return []byte{} , err
}
defer file.Close()
return ioutil.ReadAll(file)
}
4.使用bufio按照字节截断读取字节:
func bufioReadBytes(fileName string) ([]byte , error){
file , err := os.Open(fileName)
if err != nil {
return []byte{} , err
}
defer file.Close()
reader := bufio.NewReader(file)
res := []byte{}
for {
tmp , err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
return []byte{} , err
}
res = append(res,tmp...)
if err == io.EOF{
break
}
}
return res , nil
}
5.使用bufio按照字节截断读取字符串:
func bufioReadString(fileName string) (string , error) {
file , err := os.Open(fileName)
if err != nil {
return "" , err
}
defer file.Close()
res := ""
reader := bufio.NewReader(file)
for {
tmp , err := reader.ReadString('\n')
if err != nil && err != io.EOF {
return "" , err
}
res += tmp
if err == io.EOF {
break
}
}
return res , nil
}
网友评论