一、读写文件

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('\n') //读到换行就结束
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\n")
write.WriteString("2\n")
//使用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=======\n")
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

  

golang文件操作的更多相关文章

  1. Golang文件操作整理

    基本操作 文件创建 创建文件的时候,一定要注意权限问题,一般默认的文件权限是 0666 关于权限的相关内容,具体可以参考鸟叔p141 这里还是再回顾下,文件属性 r w x r w x r w x,第 ...

  2. golang 文件操作

    package main import (     "bytes"     "fmt"     "io"     "os" ...

  3. GO语言的进阶之路-Golang字符串处理以及文件操作

    GO语言的进阶之路-Golang字符串处理以及文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们都知道Golang是一门强类型的语言,相比Python在处理一些并发问题也 ...

  4. golang中的文件操作

    一.文件的基本介绍 文件是数据源(保存数据的地方)的一种,比如经常使用的word文档,txt文件,excel文件都是文件.文件最主要的作用就是保存数据,它既可以保存一张图片,也可以保持视频,声音等等. ...

  5. Golang字符串处理以及文件操作

    一.整数 1.int与uint的初值比较以及其大小. 1 /* 2 #!/usr/bin/env gorun 3 @author :xxxx 4 Blog:http://www.cnblogs.com ...

  6. golang基础知识之文件操作

    读取文件所有内容以及获得文件操作对象 package mainimport ( "bufio" "fmt" "io" "io/io ...

  7. golang之终端操作,文件操作

    终端操作 操作终端相关的文件句柄常量os.Stdin:标准输入os.Stdout:标准输出os.Stderr:标准错误输出 关于终端操作的代码例子: package main import " ...

  8. Golang: 读写之外的其他文件操作

    在上一篇文章中,我们介绍了常用的文件读写操作,今天接着来研究一下,除了读写以外的其他常见文件操作. 一.创建目录: package main import ( "fmt" &quo ...

  9. golang 之文件操作

    文件操作要理解一切皆文件. Go 在 os 中提供了文件的基本操作,包括通常意义的打开.创建.读写等操作,除此以外为了追求便捷以及性能上,Go 还在 io/ioutil 以及 bufio 提供一些其他 ...

随机推荐

  1. springboot~使用docker构建gradle项目

    这是一篇关系到四个知识点的文章,分别是java,docker,springboot和gradle,我们希望在java环境下,使用springboot框架,通过gradle去构建项目,然后把项目部署和运 ...

  2. springboot~maven制作底层公用库

    把一些公用方法,类型抽象到一个项目里,让其它项目依赖它,这种设计是一种解耦的体现,其实像springboot就是我们的一种依赖,他里面有很多子模块,用到哪个就添加哪个依赖即可,像redis,mongo ...

  3. DotNetCore跨平台~EFCore数据上下文的创建方式

    回到目录 对于DotNetCore来说,把大部分组件者放在DI容器里,在startup中进行注入,在类的构造方法中进行使用,如果某些情况下,无法使用这种DI的方式,也可以自己控制数据上下文的生产过程, ...

  4. SmartSql Map

    SmartSqlMap 属性 说明 Scope 域,用于SqlMap定义Sql声明范围 Statement标签 属性 说明 Id 唯一性编号 Cache 缓存策略编号,引用自Cache标签 State ...

  5. sql小知识点

    1]sql去重复 select * from View where SfzId in ())

  6. [TCP/IP] 传输层-TCP和UDP的使用场景

    传输层-TCP和UDP应用场景 TCP(传输控制协议) 需要将要传输的文件分段传输,建立会话,可靠传输,流量控制 UDP(用户报文协议) 一个数据包就能完成数据通信,不需要建立会话,不分段,不用流量控 ...

  7. oracle学习笔记(三) DCL 数据控制语言与 DDL 数据定义语言

    DCL 数据控制语言 Data control language 之前说过的授权和收权利语句 grant, revoke DDL 数据定义语言 Data define language create ...

  8. 将传统 WPF 程序迁移到 DotNetCore 3.0

    介绍 由于历史原因,基于 Windows 平台存在着大量的基于 .NetFramework 开发的 WPF 和 WinForm 相关程序,如果将这些程序全部基于 DotNetCore 3.0 重写一遍 ...

  9. 自己实现的TypeOf函数2

    自己实现的typeOf函数:返回传入参数的类型 主要用于解决,js自带的typeof返回结果不精确:Ext JS中typeOf对字符串对象.元素节点.文本节点.空白文本节点判断并不准确的问题 与上一篇 ...

  10. vue 数据改变但是视图没更新

    在使用过程中会出现数据改变但是视图没有更新的情况(类型数组或者对象),这里我们就需要用到 $set 如果是对象类型: this.$set(this.userInfo, 'name', 'gionlee ...