go入坑记录 文件断点重传

打印 上一主题 下一主题

主题 977|帖子 977|积分 2933

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
断点续传  本质上还是文件的复制边复制边记录复制的字节数(ps: 要设置好临时文件的权限,我刚开始没设置好,每次都给我新建一个空白的,断了以后从0给我传)
  1. 1 package main
  2. 2
  3. 3 import (
  4. 4     "fmt"
  5. 5     "io"
  6. 6     "log"
  7. 7     "os"
  8. 8     "strconv"
  9. 9     "strings"
  10. 10 )
  11. 11
  12. 12 /*
  13. 13 断点续传  本质上还是文件的复制
  14. 14 边复制边记录复制的字节数
  15. 15 */
  16. 16 func main() {
  17. 17     srcFile := "E:\\2019.12\\03.jpeg"
  18. 18     destFile := srcFile[strings.LastIndex(srcFile, "\")+1:]
  19. 19     fmt.Println(destFile)
  20. 20     tempFile := destFile + "temp.txt"
  21. 21     fmt.Println(tempFile)
  22. 22     file1, err := os.Open(srcFile)
  23. 23     file2, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, os.ModePerm)
  24. 24     file3, err := os.OpenFile(tempFile, os.O_RDWR|os.O_CREATE, os.ModePerm)
  25. 25     HandleErr(err)
  26. 26
  27. 27     defer file1.Close()
  28. 28     defer file2.Close()
  29. 29
  30. 30     //1,先读取临时文件的数据,再seek
  31. 31     file3.Seek(0, io.SeekStart)
  32. 32     bs := make([]byte, 1000, 1000)
  33. 33     n1, err := file3.Read(bs)
  34. 34     countStr := string(bs[:n1])
  35. 35     count, err := strconv.ParseInt(countStr, 10, 64)
  36. 36     fmt.Println("临时文件:", count)
  37. 37
  38. 38     //2,设置读,写的位置
  39. 39     file1.Seek(count, io.SeekStart)
  40. 40     file2.Seek(count, io.SeekStart)
  41. 41     data := make([]byte, 10*1024, 10*1024)
  42. 42     // n2 := -1            //读的位置
  43. 43     // n3 := -1            //写的位置
  44. 44     total := int(count) //读取的总量
  45. 45
  46. 46     //3, 复制文件
  47. 47     for {
  48. 48         n2, err := file1.Read(data)
  49. 49         if err == io.EOF || n2 == 0 {
  50. 50             fmt.Println("复制完毕", total)
  51. 51             file3.Close()
  52. 52             os.Remove(tempFile)
  53. 53             break
  54. 54         }
  55. 55         n3, err := file2.Write(data[:n2])
  56. 56         total += n3
  57. 57         file3.Seek(0, io.SeekStart)
  58. 58         file3.WriteString(strconv.Itoa(total))
  59. 59
  60. 60         fmt.Printf("total:%d\n", total)
  61. 61         //假装断电
  62. 62         // if total > 100000 {
  63. 63         //     panic("断电了。。。。。")
  64. 64         // }
  65. 65     }
  66. 66 }
  67. 67
  68. 68 func HandleErr(err error) {
  69. 69     if err != nil {
  70. 70         log.Fatal(err)
  71. 71     }
  72. 72 }
复制代码
凑字数
凑字数凑字数
凑字数凑字数凑字数

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

祗疼妳一个

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表