Go-文件(2)
将一个文件内容写入到另一个文件
package main
import (
"fmt"
"io/ioutil"
)
func main() {
file1Path := "C:/Users/pc/Desktop/1.txt"
file2Path := "C:/Users/pc/Desktop/2.txt"
data, err := ioutil.ReadFile(file1Path)
if err != nil {
fmt.Printf("err=%v", err)
return
}
err = ioutil.WriteFile(file2Path, data, 0666)
if err != nil {
fmt.Printf("err=%v", err)
}
}
判断文件是否存在
拷贝文件
将一张照片/电影/MP3拷贝到另一个目录下
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {
srcfile, err := os.Open(srcFileName)
if err != nil {
fmt.Printf("err=%v", err)
}
defer srcfile.Close()
reader := bufio.NewReader(srcfile)
dstfile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("err=%v", err)
return
}
writer := bufio.NewWriter(dstfile)
defer dstfile.Close()
return io.Copy(writer, reader)
}
func main() {
//将flower.jpg文件拷贝到abc.jpg
srcfile := "C:/Users/pc/Desktop/1/1.png"
dstfile := "C:/Users/pc/Desktop/2/2.png"
_, err := CopyFile(dstfile, srcfile)
if err == nil {
fmt.Println("拷贝完成")
} else {
fmt.Printf("err=%v", err)
}
}
统计英文、数字、空格和其他字符数量
package main
import (
"bufio"
"fmt"
"io"
"os"
)
type CharCount struct {
chCount int
NumCount int
SpaceCount int
OtherCount int
}
func main() {
//将flower.jpg文件拷贝到abc.jpg
filePath := "C:/Users/pc/Desktop/1/1.txt"
srcfile, err := os.Open(filePath)
if err != nil {
fmt.Printf("err=%v", err)
return
}
defer srcfile.Close()
reader := bufio.NewReader(srcfile)
var count CharCount
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
break
}
for _, v := range str {
switch {
case v >= 'a' && v <= 'z':
fallthrough
case v >= 'A' && v <= 'Z':
count.chCount++
case v == ' ' || v == '\t':
count.SpaceCount++
case v >= '0' && v <= '9':
count.NumCount++
default:
count.OtherCount++
}
}
}
fmt.Printf("字符的个数为=%v 数字的个数为=%v 空格的个数为=%v 其他字符的个数为=%v",
count.chCount, count.NumCount, count.SpaceCount, count.OtherCount)
}
switch里面要是有判断语句 则switch就不用加条件
兼容中文字符
转载请注明出处,欢迎讨论和交流!