Hello World

go:读取、拷贝文件

1. 读取文件,打印每一行文本内容

func main() {

    // ./表示当前工程的目录
    filepath:="./source/a.txt"
    // 返回文件指针
    file, e := os.Open(filepath)
    if e != nil {
        fmt.Println("open file error",e)
        return
    }

    readLine(file)

    readBuffer(file)

    dst := "./source/b.txt"
    copyFile(dst,filepath)
}

/**
    将每行的文本内容进行打印输出
*/
func readLine(file *os.File) {

    reader := bufio.NewReader(file)
    for {
        // 设置读取结束字符,此处设置每次读取一行
        line, e := reader.ReadString('\n')
        // 读取到文件末尾
        if e == io.EOF {
            fmt.Println("read file finish")
            return
        }
        // 读取文件发生异常
        if e != nil {
            fmt.Println(e)
            return
        }
        // 打印这一行的内容
        fmt.Print(line)
    }
}

 

2. 读取文件,每次读取指定 []byte大小的内容

func main() {

    // ./表示当前工程的目录
    filepath:="./source/a.txt"
    // 返回文件指针
    file, e := os.Open(filepath)
    if e != nil {
        fmt.Println("open file error",e)
        return
    }

    readLine(file)

    readBuffer(file)

    dst := "./source/b.txt"
    copyFile(dst,filepath)
}
/**
    将缓冲区的文本内容进行打印输出
*/
func readBuffer(file *os.File) {

    reader := bufio.NewReader(file)
    // 字节缓冲区
    buf:= make([]byte,10)
    for {
        // 设置每次读取文件内容到缓冲区字节数组
        n, e := reader.Read(buf)
        // 读取到文件末尾
        if e == io.EOF {
            fmt.Println("read file finish")
            return
        }
        // 读取文件发生异常
        if e != nil {
            fmt.Println(e)
            return
        }
        var buffer bytes.Buffer
        buffer.Write(buf)
        // 打印缓冲区字节数组的内容
        fmt.Printf("read byte[] len = %d, content = %s \n",n,buffer.String())
    }
}

 

3. 拷贝文件

/**
    拷贝文件
 */
func copyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()

    dst, err := os.Create(dstName)
    if err != nil {
        return
    }
    defer dst.Close()

    return io.Copy(dst, src)
}

 

posted @ 2020-05-29 10:17  小小忧愁米粒大  阅读(308)  评论(0编辑  收藏  举报
瞅啥瞅,好好看书