Go語言複製檔案

itbsl發表於2018-12-18

需要使用io包的Copy方法

package main

import (
    "fmt"
    "io"
    "os"
)

//自己編寫一個函式,接收兩個檔案路徑 srcFileName dstFileName
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {

    srcFile, err := os.Open(srcFileName)

    if err != nil {
        fmt.Printf("open file err = %v
", err)
        return
    }

    defer srcFile.Close()

    //開啟dstFileName

    dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY | os.O_CREATE, 0755)
    if err != nil {
        fmt.Printf("open file err = %v
", err)
        return
    }

    defer dstFile.Close()

    return io.Copy(dstFile, srcFile)

}

func main() {

    result, err := CopyFile("./src/main/dst.png", "./src/main/file.png")

    if err == nil {
        fmt.Println("拷貝成功!,拷貝的位元組數為: ", result)
    }
}

還可以使用下面的方法

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

//自己編寫一個函式,接收兩個檔案路徑 srcFileName dstFileName

func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {

    srcFile, err := os.Open(srcFileName)

    if err != nil {
        fmt.Printf("open file err = %v
", err)
        return
    }

    defer srcFile.Close()

    //通過srcFile,獲取到Reader
    reader := bufio.NewReader(srcFile)

    //開啟dstFileName
    dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY | os.O_CREATE, 0666)
    if err != nil {
        fmt.Printf("open file err = %v
", err)
        return
    }

    writer := bufio.NewWriter(dstFile)
    defer func() {
        writer.Flush() //把緩衝區的內容寫入到檔案
        dstFile.Close()

    }()

    return io.Copy(writer, reader)

}

func main() {

    result, err := CopyFile("./src/main/dst.png", "./src/main/file.png")

    if err == nil {
        fmt.Println("拷貝成功!拷貝的位元組大寫為: ", result)
    }
}

相關文章