马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
断点续传 本质上还是文件的复制边复制边记录复制的字节数(ps: 要设置好临时文件的权限,我刚开始没设置好,每次都给我新建一个空白的,断了以后从0给我传)- 1 package main
- 2
- 3 import (
- 4 "fmt"
- 5 "io"
- 6 "log"
- 7 "os"
- 8 "strconv"
- 9 "strings"
- 10 )
- 11
- 12 /*
- 13 断点续传 本质上还是文件的复制
- 14 边复制边记录复制的字节数
- 15 */
- 16 func main() {
- 17 srcFile := "E:\\2019.12\\03.jpeg"
- 18 destFile := srcFile[strings.LastIndex(srcFile, "\")+1:]
- 19 fmt.Println(destFile)
- 20 tempFile := destFile + "temp.txt"
- 21 fmt.Println(tempFile)
- 22 file1, err := os.Open(srcFile)
- 23 file2, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, os.ModePerm)
- 24 file3, err := os.OpenFile(tempFile, os.O_RDWR|os.O_CREATE, os.ModePerm)
- 25 HandleErr(err)
- 26
- 27 defer file1.Close()
- 28 defer file2.Close()
- 29
- 30 //1,先读取临时文件的数据,再seek
- 31 file3.Seek(0, io.SeekStart)
- 32 bs := make([]byte, 1000, 1000)
- 33 n1, err := file3.Read(bs)
- 34 countStr := string(bs[:n1])
- 35 count, err := strconv.ParseInt(countStr, 10, 64)
- 36 fmt.Println("临时文件:", count)
- 37
- 38 //2,设置读,写的位置
- 39 file1.Seek(count, io.SeekStart)
- 40 file2.Seek(count, io.SeekStart)
- 41 data := make([]byte, 10*1024, 10*1024)
- 42 // n2 := -1 //读的位置
- 43 // n3 := -1 //写的位置
- 44 total := int(count) //读取的总量
- 45
- 46 //3, 复制文件
- 47 for {
- 48 n2, err := file1.Read(data)
- 49 if err == io.EOF || n2 == 0 {
- 50 fmt.Println("复制完毕", total)
- 51 file3.Close()
- 52 os.Remove(tempFile)
- 53 break
- 54 }
- 55 n3, err := file2.Write(data[:n2])
- 56 total += n3
- 57 file3.Seek(0, io.SeekStart)
- 58 file3.WriteString(strconv.Itoa(total))
- 59
- 60 fmt.Printf("total:%d\n", total)
- 61 //假装断电
- 62 // if total > 100000 {
- 63 // panic("断电了。。。。。")
- 64 // }
- 65 }
- 66 }
- 67
- 68 func HandleErr(err error) {
- 69 if err != nil {
- 70 log.Fatal(err)
- 71 }
- 72 }
复制代码 凑字数
凑字数凑字数
凑字数凑字数凑字数
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |