(三十六)golang--文件的基本操作
文件程序中是以流的形式操作的。 流:数据在数据源(文件)和程序(内存)之间经历的路径; 输入流:数据从数据源到程序的路径; 输出流:数据从程序到数据源的路径; 常用的文件操作和函数: 1.常用的文件操作函数和方法(打开和关闭文件) 2.读取文件中的内容,并显示给终端(带缓冲区的方式),使用os.Open(),file.Close(),bufio.NewReader(),reader.ReadString() 3.读取文件并显示在终端(使用Ioutil一次将整个文件读入到内存中) ,这种方式适用于文件不太大情况下,相关方法ioutil.ReadFile 4.写文件 (1)创建一个新文件夹,并写入hello world; (2)打开一个存在的文件,并将内容覆盖为新的; (3)打开一个存在的文件,并在末尾追加新内容; (4)打开一个存在的文件,将原来的内容读出并显示在终端,并且追加新内容; package main import ( "bufio" fmtioos" ) func main() { filepath := test.txt" //主要是参数的区别 file,err := os.OpenFile(filepath,os.O_RDWR|os.O_APPEND,0666) if err != nil { fmt.Println(open file error=n,err) } defer file.Close() reader := bufio.NewReader(file) for { str,err := reader.ReadString('n') if err == io.EOF { break } fmt.Println(str) } str := hello worldn writer := bufio.NewWriter(file) for i := 0; i < 5; i++ { writer.WriteString(str) } 因为writer是带缓存的,因此在调用WriteString的时候是先将数据存入到缓存的 因此真正写入到文件中是要用Flush方法,否则文件中会没有数据 writer.Flush() } 5.读取一个文件中的内容写到另一个文件中 6.判断文件或目录是否存在? 说明:如果文件夹存在,则返回true,nil;如果文件夹不存在,则返回false,nil;如果返回false,err,则说明是其它错误。 7.将一个目录下的图片拷贝到另一个目录下 ) func copyFile(dstFileName string,srcFileName string) (written int64,err error) { srcfile,err := os.Open(srcFileName) open file error= bufio.NewReader(srcfile) dstfile,err := os.OpenFile(dstFileName,os.O_WRONLY|os.O_CREATE,err) } defer dstfile.Close() writer := bufio.NewWriter(dstfile) return io.Copy(writer,reader) } func main() { file1path := D:/dlrb.jpg file2path := E:/dlrb.jpg _,1)"> copyFile(file2path,file1path) 拷贝完成) } else { fmt.Println(拷贝失败 error=func main() { file1path := test1.txt srcfile,1)"> os.Open(file1path) } defer srcfile.Close() var count charCount reader := bufio.NewReader(srcfile) } for _,v := range str { fmt.Println((v)) switch { case v >= a' && v <= z: fallthrough A: count.chCount++ case v == ' ' || v == t: count.spaceCount++ 09: count.numCount++ default: count.otherCount++ } } } fmt.Printf(字符个数:%v,数字个数:%v,空格个数:%v,其它个数:%v(编辑:李大同) |
- 如何安装inf类型驱动程序 inno
- Perl v5.10.1是否有内存泄漏或如何解释valgrind
- mosquitto的TLS功能: (使用paho.mqtt.golang和JAVA版实现客
- Spring/Spring MVC/Spring Boot的区别
- Delphi 中的 XMLDocument 类详解(4) - 获取根目录下的元素数
- 利用Delphi编写Socket通信程序
- groovy / grails / unit tests / createCriteria.get
- InstallShield和InnoSetup两种打包工具的静默安装/卸载
- 找第K大数(ACdream 1099)
- Delphi中如何把函数代码调出主程序,写到“DLL”中并调用