zoukankan      html  css  js  c++  java
  • Go 文件 读写

    总结:

    写的话用   bufio.NewWriter()   wirter.WriteString()     可扩展性更强

    附 如果用户输绝对路径,就输入绝对路径,输入相对路径就拼成绝对路径

    fullPath := path.Join(_filePath, _fileName) 
        if !path.IsAbs(fullPath){
            pwd,_ := os.Getwd()
            fullPath = path.Join(pwd, fullPath)
        } 

     

     

    可以从文件读写,也可以从标准输入流读,写到控制台

    import (
        "fmt"
        "bufio"
        "os"
    )

    func main() {
        var s string
        reader := bufio.NewReader(os.Stdin)
        fmt.Printf("输入>> ")
        s,_ = reader.ReadString(' ')
        fmt.Println(s)
    }

     

    //  io包,按字节数读

    func main() {
      // 只读方式打开当前目录下的main.go文件.返回*File,err
      file, _ := os.Open("./main.go")     //  打开失败err!=nil
      // 关闭文件
      defer file.Close()
      //var tmp = make([]byte, 128)
      for{
        var tmp [128]byte
        n, err := file.Read(tmp[:])            //  n为读到的字节数n=128,读取失败err!=nil,每次读128byte
        // fmt.Println(string(tmp[:n]))       //  读到的内容在tmp切片中
        fmt.Println(n)       // 每次循环读到的字节数
        if err == io.EOF{
          return
        }
      }
    }

    //bufio按行读

    import (
      "bufio"
      "fmt"
      "io"
      "os"
    )

    // bufio按行读取示例
    func main() {
      file, _ := os.Open("./main.go")           // _为err
      defer file.Close()
      reader := bufio.NewReader(file)
      for {
        line, err := reader.ReadString(' ')                 //  注意line是字符, err != nil读取错误
        fmt.Print(line)
        if err == io.EOF {              //  读完了,再继续读,会出错err==io.EOF
        break
        }
      }
    }

    // ioutil.ReadFile读取整个文件

    package main

    import (
      "fmt"
      "io/ioutil"
    )


    func main() {
      content, err := ioutil.ReadFile("./main.go")   
      fmt.Println(string(content))
    }

     写操作

    os.OpenFile()函数能够以指定模式打开文件,从而实现文件写入相关功能。

     func OpenFile(name string, flag int, perm FileMode) (*File, error) {  // name:文件名,flag:打开文件的模式,perm:linux上的文件权限(755等)
      ...
    }

     flag:模式有以下几种:

    os.O_WRONLY        只写
    os.O_CREATE         创建文件
    os.O_RDONLY         只读
    os.O_RDWR            读写
    os.O_TRUNC          清空
    os.O_APPEND        追加

    //fmt.Fprintf

     func main() {

        file, _ := os.OpenFile("./xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)       //用逻辑或操作"|"实现不同的组合
        defer file.Close()
        fmt.Fprintf(file, "hahahhahah ")
    }

    //Write和WriteString

    func main() {
      file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)       //用逻辑或操作"|"实现不同的组合
      defer file.Close()
      str := "hello"
      file.Write([]byte(str))     //写入字节切片数据
      file.WriteString("hello boy")    //直接写入字符串数据
    }


    //bufio.NewWriter

    func main() {
      file, err := os.OpenFile("xx.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
      defer file.Close()
      writer := bufio.NewWriter(file)              // file为 *os.File类型,可以为os.Stdout标准输出
      for i := 0; i < 10; i++ {
        writer.WriteString("hello boy ")           //将数据先写入缓存
      }
      writer.Flush()      //将缓存中的内容写入文件
    }


    //ioutil.WriteFile

    import (
      "io/ioutil"
    )
    func main() {
      str := "hello"
      err := ioutil.WriteFile("./xx.txt", []byte(str), 0666)
    }

  • 相关阅读:
    ElasticSearch关闭重启命令
    解决使用驱动器中的光盘之前需要将其格式化
    mac利用Synergy操作多台电脑
    一次真实的蓝屏分析 ntkrnlmp.exe
    JS字符串false转boolean
    启明星会议室预定系统更新日志-通用版
    利用Visual Studio 2013 开发微软云Windows Azure配置指南(针对中国大陆)
    利用Bootstrap+Avalonjs+EntityFramework 开发ASP.NET WebForm应用程序(上)
    启明星会议室系统与Office365集成说明
    jQuery中attr和prop方法的区别说明
  • 原文地址:https://www.cnblogs.com/staff/p/13226576.html
Copyright © 2011-2022 走看看