Golang File Operation III

Source: Internet
Author: User
Tags create zip md5 hash sha1
This is a creation in Article, where the information may have evolved or changed.

1. Packaging files

//This example uses zip but the standard library//also supports tar archivespackage mainimport ("Archive/zip" " Log "" OS ") Func main () {//Create a packaged file OutFile, err: = OS. Create ("Test.zip") if err! = Nil {log. Fatal (ERR)} defer outfile.close ()//create zip writer zipwriter: = zip. Newwriter (outFile)//write files to the package file. Here we use hard-coded content, you can traverse a folder, the files under the folder and their contents into the package file. var filestoarchive = []struct {Name, Body string} {{"Test.txt", "String contents of File"}, {"T Est2.txt "," \x61\x62\x63\n "},}//the content to be packaged below is written to the packaged file, and then to the. For _, File: = Range filestoarchive {fileWriter, err: = Zipwriter.create (file. Name) If err! = Nil {log. Fatal (Err)} _, Err = Filewriter.write ([]byte (file. Body)) If err! = Nil {log. Fatal (ERR)}}//Clean err = Zipwriter.close () if err! = Nil {log. Fatal (Err)}} 

2.unzip

This example uses zip but standard library//also supports tar archivespackage mainimport ("Archive/zip" "Log" "IO" "OS" "Path/filepath") func main () {zipreader, err: = Zip. Openreader ("Test.zip") if err! = Nil {log. Fatal (ERR)} defer zipreader.close ()//Traverse each file/folder in the package file for _, File: = Range ZipReader.Reader.File {/ /package files in a file just like a normal file object Zippedfile, Err: = file. Open () if err! = Nil {log.        Fatal (ERR)} defer zippedfile.close ()//Specifies the extracted file name.        You can specify the full pathname or a prefix so that you can place them in different folders.        Our example uses the same file name in a packaged file. TargetDir: = "./" Extractedfilepath: = filepath. Join (TargetDir, file. Name,)//Extract the project or create a folder if file. FileInfo (). Isdir () {//Create folder and set the same permissions log. Println ("Creating directory:", Extractedfilepath) os. Mkdirall (Extractedfilepath, file. Mode ())} else {//extract the normal file log. PrinTLN ("Extracting file:", file.) Name) OutputFile, err: = OS. OpenFile (Extractedfilepath, OS. O_wronly|os. O_create|os. O_trunc, file. Mode (),) if err! = Nil {log. Fatal (ERR)} defer outputfile.close ()//via IO. Copy briefly copies the contents of the file _, err = Io. Copy (OutputFile, zippedfile) if err! = Nil {log. Fatal (Err)}}}}

3. Compressing files

// 这个例子中使用gzip压缩格式,标准库还支持zlib, bz2, flate, lzwpackage mainimport (    "os"    "compress/gzip"    "log")func main() {    outputFile, err := os.Create("test.txt.gz")    if err != nil {        log.Fatal(err)    }    gzipWriter := gzip.NewWriter(outputFile)    defer gzipWriter.Close()    // 当我们写如到gizp writer数据时,它会依次压缩数据并写入到底层的文件中。    // 我们不必关心它是如何压缩的,还是像普通的writer一样操作即可。    _, err = gzipWriter.Write([]byte("Gophers rule!\n"))    if err != nil {        log.Fatal(err)    }    log.Println("Compressed data written to file.")}

4. Unzip the file

// 这个例子中使用gzip压缩格式,标准库还支持zlib, bz2, flate, lzwpackage mainimport (    "compress/gzip"    "log"    "io"    "os")func main() {    // 打开一个gzip文件。    // 文件是一个reader,但是我们可以使用各种数据源,比如web服务器返回的gzipped内容,    // 它的内容不是一个文件,而是一个内存流    gzipFile, err := os.Open("test.txt.gz")    if err != nil {        log.Fatal(err)    }    gzipReader, err := gzip.NewReader(gzipFile)    if err != nil {        log.Fatal(err)    }    defer gzipReader.Close()    // 解压缩到一个writer,它是一个file writer    outfileWriter, err := os.Create("unzipped.txt")    if err != nil {        log.Fatal(err)    }    defer outfileWriter.Close()    // 复制内容    _, err = io.Copy(outfileWriter, gzipReader)    if err != nil {        log.Fatal(err)    }}

5. Temporary Files and directories

Ioutil provides two functions: TempDir () and Tempfile ().
After the use is complete, the caller is responsible for deleting these temporary files and folders.
One advantage is that when you pass an empty string as a folder name, it creates these items in the operating system's Temp folder (/tmp on Linux).
Os. TempDir () returns the temporary folder for the current operating system.
package mainimport (     "os"     "io/ioutil"     "log"     "fmt")func main() {     // 在系统临时文件夹中创建一个临时文件夹     tempDirPath, err := ioutil.TempDir("", "myTempDir")     if err != nil {          log.Fatal(err)     }     fmt.Println("Temp dir created:", tempDirPath)     // 在临时文件夹中创建临时文件     tempFile, err := ioutil.TempFile(tempDirPath, "myTempFile.txt")     if err != nil {          log.Fatal(err)     }     fmt.Println("Temp file created:", tempFile.Name())     // ... 做一些操作 ...     // 关闭文件     err = tempFile.Close()     if err != nil {        log.Fatal(err)    }    // 删除我们创建的资源     err = os.Remove(tempFile.Name())     if err != nil {        log.Fatal(err)    }     err = os.Remove(tempDirPath)     if err != nil {        log.Fatal(err)    }}

6. downloading files via HTTP

package mainimport (     "os"     "io"     "log"     "net/http")func main() {     newFile, err := os.Create("devdungeon.html")     if err != nil {          log.Fatal(err)     }     defer newFile.Close()     url := "http://www.devdungeon.com/archive"     response, err := http.Get(url)     defer response.Body.Close()     // 将HTTP response Body中的内容写入到文件     // Body满足reader接口,因此我们可以使用ioutil.Copy     numBytesWritten, err := io.Copy(newFile, response.Body)     if err != nil {          log.Fatal(err)     }     log.Printf("Downloaded %d byte file.\n", numBytesWritten)}

7. Hashes and summaries

package mainimport (    "crypto/md5"    "crypto/sha1"    "crypto/sha256"    "crypto/sha512"    "log"    "fmt"    "io/ioutil")func main() {    // 得到文件内容    data, err := ioutil.ReadFile("test.txt")    if err != nil {        log.Fatal(err)    }    // 计算Hash    fmt.Printf("Md5: %x\n\n", md5.Sum(data))    fmt.Printf("Sha1: %x\n\n", sha1.Sum(data))    fmt.Printf("Sha256: %x\n\n", sha256.Sum256(data))    fmt.Printf("Sha512: %x\n\n", sha512.Sum512(data))}

The above example copies the entire contents of the file into memory and passes it to the hash function.
Another way is to create a hash writer that passes the data to it using write, writestring, and copy.
The following example uses the MD5 hash, but you can use the other writer.

package mainimport (    "crypto/md5"    "log"    "fmt"    "io"    "os")func main() {    file, err := os.Open("test.txt")    if err != nil {        log.Fatal(err)    }    defer file.Close()    //创建一个新的hasher,满足writer接口    hasher := md5.New()    _, err = io.Copy(hasher, file)    if err != nil {        log.Fatal(err)    }    // 计算hash并打印结果。    // 传递 nil 作为参数,因为我们不通参数传递数据,而是通过writer接口。    sum := hasher.Sum(nil)    fmt.Printf("Md5 checksum: %x\n", sum)}

Original: http://colobu.com/2016/10/12/...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.