zoukankan      html  css  js  c++  java
  • golang文件操作

    一、读写文件

    1、读文件操作


    os.File 封装所有文件相关操作

    例子:

    package main
    import (
        "fmt"
        "os"
        "io/ioutil"
        "bufio"
        "io"
    )
    
    func main(){
        file,err := os.Open("/etc/hosts")
        if err != nil {
            fmt.Println("error!")
        }
        fmt.Println("file",file)  //获取的是指针
        
        //
        reader := bufio.NewReader(file)    
        for {
            str,err := reader.ReadString('
    ') //读到换行就结束
            if err == io.EOF { //io.EOF表示文件结尾
                break
            }
            fmt.Printf(str)
        }
    
        err = file.Close() //关闭文件
        if err != nil{
            fmt.Println("file close error!",err)
        }
          
    
        fmt.Println("======ioutil==========")
    
        //ioutil一次将整个文件读入到内存中,适合小文件
        file2,err := ioutil.ReadFile("/etc/hosts")
        fmt.Println(file2) //[]byte
        fmt.Println(string(file2)) 
    
    }
    
    
    ##结果####
    file &{0xc42005c0f0}
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    ======ioutil==========
    [49 50 55 46 48 46 48 46 49 32 32 32 108 111 99 97 108 104 111 115 116 32 108 111 99 97 108 104 111 115 116 46 108 111 99 97 108 100 111 109 97 105 110 32 108 111 99 97 108 104 111 115 116 52 32 108 111 99 97 108 104 111 115 116 52 46 108 111 99 97 108 100 111 109 97 105 110 52 10 58 58 49 32 32 32 32 32 32 32 32 32 108 111 99 97 108 104 111 115 116 32 108 111 99 97 108 104 111 115 116 46 108 111 99 97 108 100 111 109 97 105 110 32 108 111 99 97 108 104 111 115 116 54 32 108 111 99 97 108 104 111 115 116 54 46 108 111 99 97 108 100 111 109 97 105 110 54 10]
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    

      

    2、文件写操作

    os.OpenFile是一个一般性的文件打开函数,参数如下 (第一个参数是文件地址,第二个参数如下,可以组合使用,第三个参数是控制文件的权限)

    os.O_CREATE 文件不存在就会创建
    os.O_APPEND 以追加内容的形式添加
    os.O_WRONLY 只写模式
    os.O_RDONLY 只读模式
    os.O_RDWR 读写模式
    os.O_EXCL 和os.O_CREATE配合使用,文件必须不存在
    os.O_SYNC 打开文件用于同步I/O
    os.O_TRUNC 打开时清空文件

    例子:

    package main
    import (
        "fmt"
        "bufio"
        "os"
    )
    
    
    func main(){
        //创建新文件
        filename := "/tmp/a.txt"
        file,err := os.OpenFile(filename,os.O_WRONLY|os.O_CREATE,0600)
        if err != nil {
            fmt.Println("open file error",err)
        }
    
       //及时关闭file句柄
        defer file.Close()
       //写入到缓存的*write
        write := bufio.NewWriter(file)
        write.WriteString("1
    ")
        write.WriteString("2
    ")
        //使用Flush方法,将数据写入到文件中
        write.Flush()
        //追加内容
        file2,err := os.OpenFile("/etc/hosts",os.O_WRONLY|os.O_APPEND,0644)
        if err != nil {
            fmt.Println("open file error",err)
        }
        insert := bufio.NewWriter(file2)
        insert.WriteString("==============go=======
    ")
        insert.Flush()
    }
    
    
    ##结果####
    [root@localhostgo_test]#ll /tmp/a.txt 
    -rw------- 1 root root 4 3月  21 14:27 /tmp/a.txt
    [root@localhostgo_test]#cat /tmp/a.txt 
    1
    2
    
    [root@localhostgo_test]#cat /etc/hosts
    127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
    ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
    ==============go=======
    

      

     二、复制文件

    代码:

    package main
    
    import (
        "fmt"
        "io"
        "os"
    )
    func main() {
        CopyFile(os.Args[1], os.Args[2]) // os.Args[1]为目标文件,os.Args[2]为源文件
        fmt.Println("复制完成")
    }
    func CopyFile(dstName, srcName string) (written int64, err error) {
        src, err := os.Open(srcName)
        if err != nil {
            return
        }
        defer src.Close()
        dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
        if err != nil {
            return
        }
        defer dst.Close()
        return io.Copy(dst, src)
    }
    

      

    使用测试:

    [root@localhostgo_test]#cat /tmp/a.txt 
    1
    2
    [root@localhostgo_test]#go run copy_file.go  /tmp/copy_a.txt  /tmp/a.txt 
    复制完成
    [root@localhostgo_test]#cat /tmp/copy_a.txt 
    1
    2
    

      

  • 相关阅读:
    [Swift]LeetCode900. RLE 迭代器 | RLE Iterator
    TNS-12508 When Issuing Any SET Command For The Listene
    shell getopts
    archive log full ora-00257
    php 验证码
    php 缩略图
    弧度
    php输出中文字符
    流程图
    windows clone 迁移数据库
  • 原文地址:https://www.cnblogs.com/zhangb8042/p/10571556.html
Copyright © 2011-2022 走看看