我們可以利用讀寫來複制文件,也可以在複製的同時,再新建一個臨時文件保存讀寫的進度,如果有意外發生,我們還可以通過臨時文件中的進度,來繼續複製文件
package main import ( "os" "fmt" "strconv" "io" ) func main() { /* 思路:斷點續傳,邊複製,邊記錄複製的數據量 */ srcName:="C:\\liu\\pro\\aa.jpeg" destName:="C:\\liu\\bb.jpeg" file1,_:=os.Open(srcName) //目標文件打開 file2,_:=os.OpenFile(destName,os.O_WRONLY|os.O_CREATE,os.ModePerm)//要把文件複製到哪裏,創建一個新文件 tempName :=destName+"temp.txt" //C:\\liu\\bb.jpegtemp.txt file3,_:=os.OpenFile(tempName,os.O_RDWR|os.O_CREATE,os.ModePerm) //新建臨時文件 defer file1.Close() defer file2.Close() //defer file3.Close() //1.從臨時文件中讀取已經存儲的上次的拷貝的數據量 totalBytes:=make([] byte,100) count1,_:=file3.Read(totalBytes) // 將已經拷貝的數據量讀取到數組中 totalStr := string(totalBytes[:count1])// 從數組中獲取讀取的數量量,-->string total,_ := strconv.Atoi(totalStr) //int fmt.Println("上次已經複製的數據量",total) //2.設置讀寫的位置 file1.Seek(int64(total),0) file2.Seek(int64(total),0) dataBytes:=make([] byte, 1024) for{ count2,err:= file1.Read(dataBytes) if err == io.EOF { fmt.Println("已經複製到文件末尾。。", total) file3.Close() os.Remove(tempName) break } file2.Write(dataBytes[:count2]) total += count2 file3.Seek(0,0) totalStr=strconv.Itoa(total) file3.WriteString(totalStr) //if total > 30000{ // panic("意外斷點了,,假裝的。。。。") //} } }