• 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('
    ')
            // 读取到文件末尾
            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,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)
    }
  • 相关阅读:
    最容易懂的红黑树
    Chapter 9 (排序)
    【WC2013】糖果公园
    【Luogu1903】数颜色
    【笔记】Sigmoid函数
    【笔记】费马小定理、数论欧拉定理
    【笔记】单层感知机
    2020ICPC.小米 网络选拔赛第一场
    【Luogu3366】模板:最小生成树
    Codeforces Raif Round 1
  • 原文地址:https://www.cnblogs.com/virgosnail/p/12985905.html
Copyright © 2020-2023  润新知