Go语言入门(九) 文件操作

文件操作

文件的基本操作

读文件

func readFile(){
   filename :=  "./aaa.log"

   file, err := os.Open(filename)
   if err != nil {
      fmt.Printf("open %s is error,error %v\n",filename,err)
      return
   }
   //关闭文件句柄
   defer func() {
      file.Close()
   }()
   //读取文件
   var buf[4096]byte
   var content []byte
   for {
      n,err := file.Read(buf[:])
      if err != nil && err != io.EOF {
         fmt.Printf("Read %s failed,error %v\n",filename,err)
         return
      }
      //读取到文件末尾
      if err == io.EOF {
         break
      }
      validBuf := buf[0:n]
      //fmt.Printf("%s\n",string(validBuf))
      content = append(content,validBuf...)
   }
   fmt.Printf("content :%s\n",content)

}

func main() {
   readFile()
}
  • 使用bufio来提高文件读取的性能
func buffioRead() {
   //使用缓存的方式读取文件
   filename := "./aaa.log"
   file,err := os.Open(filename)
   if err != nil {
      fmt.Printf("read file %s faild,error :%v\n",filename,err)
      return
   }

   defer file.Close()

   reader := bufio.NewReader(file)

   var content []byte
   var buf [4096]byte

   for {
      n,err := reader.Read(buf[:])
      if err != nil && err != io.EOF {
         fmt.Printf("read %s failed,error is :%v\n",filename,err)
         return
      }
      //读取到文件末尾
      if err == io.EOF {
         break
      }
      validBuf := buf[0:n]
      content = append(content,validBuf...)
   }
   fmt.Printf("content :%s\n",content)

}

func main() {
   buffioRead()
}
  • ioutil文件读取整个文件: 读取小文件使用,比如配置文件需求
func ioutilRead(){
   filename := "./aaa.log"
   content,err := ioutil.ReadFile(filename)
   if err != nil {
      fmt.Printf("read file %s error :%v\n",filename,err)
      return
   }
   fmt.Printf("content %s\n",string(content))
}
  • 读取压缩文件
文件压缩: gzip -c 源文件 > 压缩文件.gz
目录压缩: gzip -r 目录
解压: gzip -d 压缩文件.gz
  • gz文件读取代码
func gzfileRead() {
   filename := "./aaa.gz"
   file,err := os.Open(filename)
   if err !=nil {
      fmt.Printf("can not open %s,err: %v\n",filename,err)
      return
   }

   defer file.Close()

   reader,err := gzip.NewReader(file)
   if err != nil {
      fmt.Printf("gzfile read faild,err: %v\n",err)
      return
   }
   // reader := bufio.NewReader(file)  读取出来的内容是二进制的

   var content []byte
   var buf [4096]byte
   for {
      n,err := reader.Read(buf[:])
      if err != nil && err != io.EOF {
         fmt.Printf("read %s faild,err: %v\n",filename,err)
         return
      }
      if n > 0 {
         validBuf := buf[0:n]
         content = append(content,validBuf...)
      }
      if err == io.EOF {
         break
      }
   }
   fmt.Printf("content,:%s\n",string(content))
}

写文件

func checkFileExists(filename string) bool {
   // 文件存在检测
   _,err := os.Stat(filename)
   if os.IsNotExist(err) {
      return false
   }
   return true
}

func createWriteFiles() {
   filename := "./bbb.txt"
   var file *os.File
   var err error

   // 文件追加或创建
   if checkFileExists(filename) {
      file,err = os.OpenFile(filename,os.O_APPEND|os.O_WRONLY,0755)
   }else {
      file,err = os.Create(filename)
   }
   if err != nil {
      fmt.Printf("create file %s,error :%v \n", filename, err)
      return
   }
   defer file.Close()
   //写入文件
   n,err := file.WriteString("hello world")
   if err != nil {
      fmt.Printf("write faild,err: %v\n",err)
      return
   }
   fmt.Printf("write %d succ\n",n)
}
  • 使用ioutil直接写入:可以覆盖文件
func ioutilWrite() {
   filename := "./bbb.txt"
   str := "ssssaddvfv"
   ioutil.WriteFile(filename,[]byte(str),0755)
}
  • 使用bufio写入文件: 可能会导致数据丢失
func checkFileExists(filename string) bool {
   // 文件存在检测
   _,err := os.Stat(filename)
   if os.IsNotExist(err) {
      return false
   }
   return true
}

func bufioWriteFile() {
   filename := "./ccc.txt"
   var file *os.File
   var err error
   if checkFileExists(filename) {
      file,err = os.OpenFile(filename,os.O_WRONLY|os.O_APPEND,0666)
   }else {
      file,err = os.Create(filename)
   }
   if err != nil {
      fmt.Printf("write file error:%v\n",err)
      return
   }

   defer file.Close()

   //bufio文件写入
   writer := bufio.NewWriter(file)
   writer.WriteString("helloworld,wxxx")
   writer.Flush()   //将缓存数据刷到文件
}
  • 拷贝文件
func copyFile(destFile,srcFile string) (written int64,err error) {
   src,err := os.Open(srcFile)
   if err != nil {
      fmt.Printf("open src file error:%v\n",err)
      return
   }
   defer src.Close()

   dst,err := os.OpenFile(destFile,os.O_WRONLY|os.O_APPEND,0666)
   if err != nil {
      return
   }
   return io.Copy(dst,src)
}

func main()  {
   copyFile("./ddd.txt","aaa.log")
}
  • 终端读写
func terminalControl() {
   writer := bufio.NewWriter(os.Stdout)
   writer.WriteString("hello")
   writer.Flush()

   //读取终端数据
   reader := bufio.NewReader(os.Stdin)
   data,err := reader.ReadString(‘\n‘)

   if err != nil {
      fmt.Printf("read fro  terminal error:%v\n",err)
   }

   fmt.Fprintf(os.Stdout,"data:%s\n",data)
}
  • 小练习:统计终端输入的字母数字空格的数量
func addWord(charCount map[rune]int,char rune){
   count,ok := charCount[char]
   if !ok {
      charCount[char] = 1
   }else {
      charCount[char] = count +1
   }
}

func main() {
   str := ""
   fmt.Scanln(&str)

   writer := bufio.NewWriter(os.Stdout)
   writer.WriteString("")
   writer.Flush()

   //读取终端数据
   reader := bufio.NewReader(os.Stdin)
   data,err := reader.ReadString(‘\n‘)

   if err != nil {
      fmt.Printf("read fro  terminal error:%v\n",err)
   }

   fmt.Fprintf(os.Stdout,"data:%s\n",data)
   var charCount map[rune]int = make(map[rune]int,10)
   var chars []rune = []rune(data)

   for i:=0;i<len(chars);i++ {
      addWord(charCount,chars[i])
   }

   for key,val := range charCount {
      fmt.Printf("keys:%c val: %d\n",key,val)
   }
}

命令行参数

func main() {
   //获取参数个数
   fmt.Printf("args count:%d\n",len(os.Args))
   //打印参数
   for index,v := range os.Args {
      fmt.Printf("args:%d,value:%s\n",index,v)
   }
}

flag包的使用

func flagArgs() {
   var num int
   var mode string

   flag.IntVar(&num,"num",16,"number of password")
   flag.StringVar(&mode,"mode","mix","mode of password generate")

   flag.Parse()

   fmt.Printf("num:%d,mode:%s\n",num,mode)
}

相关推荐