How to get file length in Go dynamically?

huangapple go评论105阅读模式
英文:

How to get file length in Go dynamically?

问题

我有以下代码片段:

  1. func main() {
  2. // Some text we want to compress.
  3. original := "bird and frog"
  4. // Open a file for writing.
  5. f, _ := os.Create("C:\\programs\\file.gz")
  6. // Create gzip writer.
  7. w := gzip.NewWriter(f)
  8. // Write bytes in compressed form to the file.
  9. for i := 0; i < 10; i++ {
  10. // Get the row from the database as obtained from cursor.
  11. row := []byte("row from the database")
  12. // Compress the row.
  13. compressedRow := compress(row)
  14. // Write the compressed row to the file.
  15. w.Write(compressedRow)
  16. // Check if the file size exceeds the limit.
  17. if f.Size() > 50 {
  18. // Close the current file.
  19. w.Close()
  20. f.Close()
  21. // Open a new file for writing.
  22. f, _ = os.Create("C:\\programs\\file.gz")
  23. // Create a new gzip writer.
  24. w = gzip.NewWriter(f)
  25. }
  26. }
  27. // Close the file.
  28. w.Close()
  29. f.Close()
  30. fmt.Println("DONE")
  31. }
  32. func compress(data []byte) []byte {
  33. // Compress the data using gzip compression algorithm.
  34. // Return the compressed data.
  35. return data
  36. }

这段代码实现了在文件大小达到一定阈值时关闭当前文件并打开一个新文件的功能。在每次写入压缩文档之前,通过检查文件大小是否超过限制来判断是否需要关闭当前文件并打开一个新文件。你可以根据实际需求修改代码中的数据库行获取逻辑和压缩逻辑。

英文:

I have the following code snippet:

  1. func main() {
  2. // Some text we want to compress.
  3. original := &quot;bird and frog&quot;
  4. // Open a file for writing.
  5. f, _ := os.Create(&quot;C:\\programs\\file.gz&quot;)
  6. // Create gzip writer.
  7. w := gzip.NewWriter(f)
  8. // Write bytes in compressed form to the file.
  9. while ( looping over database cursor) {
  10. w.Write([]byte(/* the row from the database as obtained from cursor */))
  11. }
  12. // Close the file.
  13. w.Close()
  14. fmt.Println(&quot;DONE&quot;)
  15. }

However, I wish to know a small modification. When the size of file reaches a certain threshold I want to close it and open a new file. And that too in compressed format.

For example:

Assume a database has 10 rows each row is 50 bytes.

Assume compression factor is 2, ie 1 row of 50 bytes is compressed to 25 bytes.

Assume a file size limit is 50 bytes.

Which means after every 2 records I should close the file and open a new file.

How to keep track of the file size while its still open and still writing compressed documents to it ?

答案1

得分: 2

gzip.NewWriter 接受一个 io.Writer。很容易实现自定义的 io.Writer 来满足你的需求。

例如:Playground

  1. type MultiFileWriter struct {
  2. maxLimit int
  3. currentSize int
  4. currentWriter io.Writer
  5. }
  6. func (m *MultiFileWriter) Write(data []byte) (n int, err error) {
  7. if len(data)+m.currentSize > m.maxLimit {
  8. m.currentWriter = createNextFile()
  9. }
  10. m.currentSize += len(data)
  11. return m.currentWriter.Write(data)
  12. }

注意:你需要处理一些边界情况,比如如果 len(data) 大于 maxLimit 会怎样。也许你不想将一条记录拆分到多个文件中。

英文:

gzip.NewWriter takes a io.Writer. It is easy to implement custom io.Writer that does what you want.

E.g. Playground

  1. type MultiFileWriter struct {
  2. maxLimit int
  3. currentSize int
  4. currentWriter io.Writer
  5. }
  6. func (m *MultiFileWriter) Write(data []byte) (n int, err error) {
  7. if len(data)+m.currentSize &gt; m.maxLimit {
  8. m.currentWriter = createNextFile()
  9. }
  10. m.currentSize += len(data)
  11. return m.currentWriter.Write(data)
  12. }

Note: You will need to handle few edge cases like what if len(data) is greater than the maxLimit. And may be you don't want to split a record across files.

答案2

得分: 1

你可以使用os.File.Seek方法来获取文件中的当前位置,因为你正在写入文件,所以当前位置将是文件的当前大小(以字节为单位)。

例如:

  1. package main
  2. import (
  3. "compress/gzip"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. // 要压缩的文本。
  9. lines := []string{
  10. "this is a test",
  11. "the quick brown fox",
  12. "jumped over the lazy dog",
  13. "the end",
  14. }
  15. // 打开一个文件进行写入。
  16. f, err := os.Create("file.gz")
  17. if err != nil {
  18. panic(err)
  19. }
  20. // 创建gzip写入器。
  21. w := gzip.NewWriter(f)
  22. // 以压缩形式将字节写入文件。
  23. for _, line := range lines {
  24. w.Write([]byte(line))
  25. w.Flush()
  26. pos, err := f.Seek(0, os.SEEK_CUR)
  27. if err != nil {
  28. panic(err)
  29. }
  30. fmt.Printf("pos: %d\n", pos)
  31. }
  32. // 关闭文件。
  33. w.Close()
  34. // 调用w.Close()将写出任何剩余的数据和最终的校验和。
  35. pos, err := f.Seek(0, os.SEEK_CUR)
  36. if err != nil {
  37. panic(err)
  38. }
  39. fmt.Printf("pos: %d\n", pos)
  40. fmt.Println("DONE")
  41. }

输出结果为:

  1. pos: 30
  2. pos: 55
  3. pos: 83
  4. pos: 94
  5. pos: 107
  6. DONE

我们可以使用wc命令进行确认:

  1. $ wc -c file.gz
  2. 107 file.gz
英文:

You can use the os.File.Seek method to get your current position in the file, which as you're writing the file will be the current file size in bytes.

For example:

  1. package main
  2. import (
  3. &quot;compress/gzip&quot;
  4. &quot;fmt&quot;
  5. &quot;os&quot;
  6. )
  7. func main() {
  8. // Some text we want to compress.
  9. lines := []string{
  10. &quot;this is a test&quot;,
  11. &quot;the quick brown fox&quot;,
  12. &quot;jumped over the lazy dog&quot;,
  13. &quot;the end&quot;,
  14. }
  15. // Open a file for writing.
  16. f, err := os.Create(&quot;file.gz&quot;)
  17. if err != nil {
  18. panic(err)
  19. }
  20. // Create gzip writer.
  21. w := gzip.NewWriter(f)
  22. // Write bytes in compressed form to the file.
  23. for _, line := range lines {
  24. w.Write([]byte(line))
  25. w.Flush()
  26. pos, err := f.Seek(0, os.SEEK_CUR)
  27. if err != nil {
  28. panic(err)
  29. }
  30. fmt.Printf(&quot;pos: %d\n&quot;, pos)
  31. }
  32. // Close the file.
  33. w.Close()
  34. // The call to w.Close() will write out any remaining data
  35. // and the final checksum.
  36. pos, err := f.Seek(0, os.SEEK_CUR)
  37. if err != nil {
  38. panic(err)
  39. }
  40. fmt.Printf(&quot;pos: %d\n&quot;, pos)
  41. fmt.Println(&quot;DONE&quot;)
  42. }

Which outputs:

  1. pos: 30
  2. pos: 55
  3. pos: 83
  4. pos: 94
  5. pos: 107
  6. DONE

And we can confirm with wc:

  1. $ wc -c file.gz
  2. 107 file.gz

huangapple
  • 本文由 发表于 2022年9月14日 06:42:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/73709794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定