zoukankan      html  css  js  c++  java
  • 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)
    }
  • 相关阅读:
    李航统计学习方法(第二版)(六):k 近邻算法实现(kd树(kd tree)方法)
    ActiveMQ的安装和启动
    HTML select autofocus 属性
    macpath (File & Directory Access) – Python 中文开发手册
    Java Bitset类
    Linux zip命令
    HTML DOM Keygen 对象
    tanh (Numerics) – C 中文开发手册
    no-shadow (Rules) – Eslint 中文开发手册
    require-await (Rules) – Eslint 中文开发手册
  • 原文地址:https://www.cnblogs.com/virgosnail/p/12985905.html
Copyright © 2011-2022 走看看