斷點續傳 本質上還是檔案的復制 邊復制邊記錄復制的位元組數 (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 }
湊字數
湊字數湊字數
湊字數湊字數湊字數
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514247.html
標籤:其他
上一篇:發郵件
下一篇:java基礎-網路編程
