我有以下代碼片段:func main() { // Some text we want to compress. original := "bird and frog" // Open a file for writing. f, _ := os.Create("C:\\programs\\file.gz") // Create gzip writer. w := gzip.NewWriter(f) // Write bytes in compressed form to the file. while ( looping over database cursor) { w.Write([]byte(/* the row from the database as obtained from cursor */)) } // Close the file. w.Close() fmt.Println("DONE")}但是,我想知道一個小的修改。當文件的大小達到某個閾值時,我想關(guān)閉它并打開一個新文件。這也是壓縮格式。例如:假設(shè)一個數(shù)據(jù)庫有 10 行,每行 50 字節(jié)。假設(shè)壓縮因子為2,即1行50字節(jié)壓縮為25字節(jié)。假設(shè)文件大小限制為 50 字節(jié)。這意味著在每 2 條記錄之后我應該關(guān)閉文件并打開一個新文件。如何在文件仍然打開并向其寫入壓縮文件時跟蹤文件大???
1 回答

千巷貓影
TA貢獻1829條經(jīng)驗 獲得超7個贊
gzip.NewWriter
需要一個io.Writer
。很容易實現(xiàn)io.Writer
你想要的定制。
例如游樂場
type MultiFileWriter struct {
maxLimit int
currentSize int
currentWriter io.Writer
}
func (m *MultiFileWriter) Write(data []byte) (n int, err error) {
if len(data)+m.currentSize > m.maxLimit {
m.currentWriter = createNextFile()
}
m.currentSize += len(data)
return m.currentWriter.Write(data)
}
注意:您將需要處理一些邊緣情況,例如 iflen(data)大于maxLimit. 并且您可能不想跨文件拆分記錄。
- 1 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報
0/150
提交
取消