t3chb0t
t3chb0t

Reputation: 18626

Optimal buffer size for writing to disk while extracting ZIP files

I'm writing an unzip function for my Kotlin app and in order to report progress, I will be doing it without copyTo but via a buffer. The examples I find always use a buffer of 1024 bytes. Are there any particular reasons to keep it this size or would it be advisable to use a smaller or a larger one in certain situations?


Update: I wasn't aware of multiple buffers being used. One for extraction and one for writing. The one I mean in this question is the write buffer. Here is my code:

        fun ZipEntry.extract(zipFile: ZipFile, newFile: File, progress: (BytesWritten) -> Unit) : BytesUnzipped {
            var bytesUnzipped = 0L
            zipFile.getInputStream(this).use { input ->
                newFile.outputStream().use { output ->
                    val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
                    var bytesRead: Int
                    while (input.read(buffer).also { bytesRead = it } > 0) {
                        output.write(buffer, 0, bytesRead)
                        bytesUnzipped += bytesRead
                        progress(BytesWritten(bytesRead))
                    }
                }
            }
            return BytesUnzipped(bytesUnzipped)
        }

@JvmInline
value class BytesWritten(val value: Int)

@JvmInline
value class BytesUnzipped(val value: Long)

Upvotes: 0

Views: 67

Answers (0)

Related Questions