如何修复Windows上压缩的os.PathSeparator解压缩文件?

时间:2019-05-28 08:31:36

标签: go

我正在Windows上压缩文件,而在Linux上使用操作系统默认应用程序解压缩文件时,它不会沿着路径创建文件夹,而是创建一个名为“ indexes \ search.invcus \ index_meta.json”的文件,例如:

unzip 2019-05-23_113735_data.zip -d xfolder
Archive:  2019-05-23_113735_data.zip
  inflating: xfolder/indexes\search.invcus\index_meta.json  
  inflating: xfolder/indexes\search.invcus\store  
  inflating: xfolder/indexes\search.items\index_meta.json  
  inflating: xfolder/indexes\search.items\store  
  inflating: xfolder/indexes\search.subjects\index_meta.json  
  inflating: xfolder/indexes\search.subjects\store  
  inflating: xfolder/indexes\search.users\index_meta.json  
  inflating: xfolder/indexes\search.users\store  
  inflating: xfolder/data.db         

仅当zip文件在Linux上创建并在Windows上使用7zip等解压缩后,我才能获得正确的文件夹和文件。

func zipFiles(filename string, files []string) error {

    newZipFile, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer newZipFile.Close()

    zipWriter := zip.NewWriter(newZipFile)
    defer zipWriter.Close()

    // Add files to zip
    for _, file := range files {
        if err = addFileToZip(zipWriter, file); err != nil {
            return err
        }
    }
    return nil
}


func addFileToZip(zipWriter *zip.Writer, filename string) error {
    fileToZip, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer fileToZip.Close()

    // Get the file information
    info, err := fileToZip.Stat()
    if err != nil {
        return err
    }

    header, err := zip.FileInfoHeader(info)
    if err != nil {
        return err
    }

    // Using FileInfoHeader() above only uses the basename of the file. If we want
    // to preserve the folder structure we can overwrite this with the full path.
    header.Name = filename

    // Change to deflate to gain better compression
    // see http://golang.org/pkg/archive/zip/#pkg-constants
    header.Method = zip.Deflate

    writer, err := zipWriter.CreateHeader(header)
    if err != nil {
        return err
    }
    _, err = io.Copy(writer, fileToZip)
    return err
}

我希望:

 indexes (folder)
     search.invcus (folder)
         index_meta.json (file)

1 个答案:

答案 0 :(得分:0)

您是否签出了convert a windows created zip to Linux internal paths issue?创建该zip文件时似乎出现了问题。

或者,从这些答案中:

  

使用7z rn重命名存档中的文件,以便它们具有正斜杠。然后,当您提取存档时,将创建目录。