1. ZIP nhu mot container tren JVM
Khi nghe tu “archive”, de hinh dung ra ma thuat: “khong biet no nen/pack/unpack the nao”. Trong thuc te, huu ich hon la suy nghi don gian va hoi “chan” mot chut (tu duy chan chan — nhien lieu cho chuong trinh dang tin cay): ZIP la mot container, nghia la mot file duy nhat, ben trong chua mot tap cac phan tu. Moi phan tu co ten va tap byte (du lieu file), va doi khi con co dau hieu “day la thu muc”.
De khoi nham, mot ghi chu nho cho nguoi thich Kotlin: trong thu vien chuan Kotlin co ham zip() cho collection (ghep cac phan tu theo cap). No khong lien quan gi den ZIP archive, ngoai viec trung chu.
Trong Java/Kotlin tren JVM, ZIP thuong duoc xu ly theo dang stream thong qua cac lop trong java.util.zip. Ta se can ba “nhan vat”:
| Day la gi | Lop | Vai tro |
|---|---|---|
| “Mo ta mot phan tu trong archive” | |
Ten ben trong archive, co (flags), metadata |
| “Ghi ZIP” | |
Them entry va ghi byte vao do |
| “Doc ZIP” | |
Duyet cac entry va doc byte cua tung entry |
ZipEntry va ten ben trong archive
Neu tuong tuong ZIP nhu mot tu do, thi ZipEntry khong phai la “do vat”, ma la nhan dan len hop: hop ten gi va ben trong co gi. Trong ZipEntry dieu ta quan tam nhat la name. Day la mot chuoi mo ta “duong dan” ben trong archive: vi du docs/readme.txt hoac images/logo.png.
Va day la diem quan trong: entry.name trong nhu duong dan, nhung khong dam bao la co the an toan chuyen thang thanh duong dan tren dia. Archive co the chua nhung ten ky la nhu ../../secret.txt. Trong code san xuat (production) nguoi ta kiem tra rat nghiem ngat. Hom nay ta khong xay he thong bao mat day du, nhung van se trinh bay mot kiem tra co ban can than: khong cho phep “thoat” khoi thu muc dich khi giai nen.
Mot chi tiet nua: entry co the co dau hieu “directory” (thu muc). Trong Java dieu nay thuong duoc the hien bang viec entry.isDirectory == true (va thuong ten ket thuc bang /). Ta se tinh den dieu nay khi giai nen: thu muc thi can tao, chu khong phai “ghi byte vao trong do”.
2. Ghi ZIP
Trinh tu khi them cac entry
Ghi ZIP la noi nguoi moi thuong mac cung mot loi: quen rang archive gom nhieu entry, va moi entry co “ranh gioi” cua rieng no.
Trinh tu dung cho mot entry la: tao ZipEntry, goi putNextEntry(entry), ghi byte, goi closeEntry(). Neu ban ghi nhieu file, vong lap nay lap lai cho moi file.
Mo phong so do:
flowchart TD
A[ZipOutputStream opened] --> B["ZipEntry(name)"]
B --> C["putNextEntry(entry)"]
C --> D["copyByChunks(fileInput -> zip)"]
D --> E["closeEntry()"]
E --> F{more files?}
F -->|yes| B
F -->|no| G[ZipOutputStream closed]
Copy theo chunk: ham tien de tai su dung
Truoc khi ghi ZIP, can mot “ngua keo”: ham chuyen byte tu InputStream sang OutputStream theo tung block.
Luu y: ByteArray la mang co kich thuoc co dinh, rat tien de tai su dung lam buffer.
import java.io.InputStream
import java.io.OutputStream
fun copyByChunks(input: InputStream, output: OutputStream, bufferSize: Int = 8 * 1024): Long {
val buffer = ByteArray(bufferSize)
var total = 0L
while (true) {
val n = input.read(buffer)
if (n == -1) return total
output.write(buffer, 0, n)
total += n
}
}
Diem quan trong o day la ta ghi output.write(buffer, 0, n), chu khong ghi toan bo buffer. Block cuoi gan nhu luon nho hon kich thuoc buffer, va neu ghi du — ban se ghi them “duoi” tu cac byte cu.
Ghi ZIP don gian nhat: mot file vao archive
Tinh huong toi thieu: lay file report.bin va bo no vao backup.zip voi ten report.bin.
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
fun zipSingleFile(src: File, zipFile: File) {
ZipOutputStream(FileOutputStream(zipFile)).use { zip ->
zip.putNextEntry(ZipEntry(src.name))
FileInputStream(src).use { input -> copyByChunks(input, zip) }
zip.closeEntry()
}
}
Hay de y: copyByChunks(input, zip) hoat dong duoc vi ZipOutputStream la mot OutputStream. Doi voi no, thao tac ghi y chang “ghi vao file thuong”: chi la byte.
ZIP tu nhieu file: vong lap voi closeEntry()
Neu dong goi nhieu file, quy tac chinh khong doi: moi file tao moi ZipEntry, goi putNextEntry, copy byte, goi closeEntry().
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
fun zipFiles(files: List<File>, zipFile: File) {
ZipOutputStream(FileOutputStream(zipFile)).use { zip ->
for (f in files) {
zip.putNextEntry(ZipEntry(f.name))
FileInputStream(f).use { input -> copyByChunks(input, zip) }
zip.closeEntry()
}
}
}
Neu muon kiem tra nhanh ket qua (khong dung cryptography hay hash), it nhat co the in ra kich thuoc archive tren dia. Dieu nay khong chung minh dung, nhung giup nhan ra “archive rong” vo tinh tao ra do loi.
import java.io.File
fun main() {
val zip = File("backup.zip")
println("zipSize=${zip.length()}") // zipSize=...
}
3. Doc ZIP va giai nen
ZipInputStream, nextEntry va doc tuan tu
Doc ZIP duoc thiet ke khac doc mot thu muc thong thuong: ZipInputStream doc archive theo tuan tu, entry nay den entry khac.
API then chot: zip.nextEntry. No tra ve ZipEntry?. Neu tra ve null thi het entry. Khi entry dang hoat dong, zip tuong tu nhu InputStream nhung chi cho du lieu cua entry do: ban goi zip.read(buffer) va nhan byte cua file.
Mini-tien ich “hien thi ben trong archive co gi” (khong giai nen):
import java.io.FileInputStream
import java.util.zip.ZipInputStream
fun listZip(zipPath: String) {
ZipInputStream(FileInputStream(zipPath)).use { zip ->
var entry = zip.nextEntry
while (entry != null) {
println("entry=${entry.name}, dir=${entry.isDirectory}")
zip.closeEntry()
entry = zip.nextEntry
}
}
}
closeEntry() khi doc cung quan trong. Ke ca neu o dau do “tu no van chay”, tot hon la giu ky luat: “dong entry” — “chuyen sang entry tiep theo”.
Giai nen: thu muc, thu muc cha va duong dan an toan
Giai nen la noi copy theo chunk lai dong vai chinh. Ta lay ZipInputStream, duyet qua cac entry, va voi moi entry “la file” ta tao FileOutputStream trong thu muc dich, sau do chuyen byte theo block: copyByChunks(zip, out).
Co ba van de thuc te nen giai quyet ke ca trong phien ban hoc tap:
- Van de thu nhat — thu muc. Neu entry la thu muc, ta phai tao no (mkdirs()), chu khong co “ghi byte vao thu muc”.
- Van de thu hai — thu muc cha cua file. Neu entry ten la docs/readme.txt, thi thu muc docs phai ton tai. Vi vay truoc khi ghi file can goi outFile.parentFile?.mkdirs().
- Van de thu ba — ten khong an toan. Cach toi thieu dung: tao duong dan dich, normalize/canonicalize va kiem tra rang no van nam ben trong outDir.
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipInputStream
private fun resolveSafely(outDir: File, entryName: String): File? {
val target = File(outDir, entryName)
val outDirCanonical = outDir.canonicalFile
val targetCanonical = target.canonicalFile
return if (targetCanonical.path.startsWith(outDirCanonical.path + File.separator)) {
targetCanonical
} else {
null
}
}
fun unzipAll(zipFile: File, outDir: File) {
outDir.mkdirs()
ZipInputStream(FileInputStream(zipFile)).use { zip ->
var entry = zip.nextEntry
while (entry != null) {
val outFile = resolveSafely(outDir, entry.name)
if (outFile != null) {
if (entry.isDirectory) {
outFile.mkdirs()
} else {
outFile.parentFile?.mkdirs()
FileOutputStream(outFile).use { out ->
copyByChunks(zip, out)
}
}
}
zip.closeEntry()
entry = zip.nextEntry
}
}
}
Neu de y ky, code trong giong het “copy thong thuong”, chi khac la input stream cua file khong phai FileInputStream, ma la ZipInputStream, cai dang “tro vao” du lieu cua entry hien tai.
4. Mini-CLI va nhung diem can biet
Lenh zip, unzip, list trong mot main()
Khi dang hoc, rat de bien du an thanh bo suu tap cac main() roi rac. De luyen tap tien hon, hay lam mot dau vao CLI don gian, goi cac ham cua ta.
Parse se lam cuc ky don gian: doc chuoi, tach theo khoang trang, lay cac tu dau. Khong lam “parse thong minh” cho dau ngoac kep va khoang trang trong duong dan — hien tai khong phai muc tieu.
import java.io.File
fun main() {
while (true) {
print("filelab> ")
val line = readln().trim()
if (line.isEmpty()) continue
val parts = line.split(" ")
when (parts[0]) {
"exit" -> return
"list" -> {
if (parts.size < 2) println("Usage: list <zipPath>")
else listZip(parts[1])
}
"zip" -> {
if (parts.size < 3) println("Usage: zip <srcFile> <zipFile>")
else zipSingleFile(File(parts[1]), File(parts[2]))
}
"unzip" -> {
if (parts.size < 3) println("Usage: unzip <zipFile> <outDir>")
else unzipAll(File(parts[1]), File(parts[2]))
}
else -> println("Unknown command")
}
}
}
Nuances: bo nho va bao mat duong dan
ZIP voi tu cach dinh dang lam duoc nhieu: nen (nhieu thuat toan), mat khau (ngoai doi hay khong tuong thich), comment, thuoc tinh he file. Ta khong ban toi. Nhung co hai diem “tranh dap phai cao” nen nho.
Diem thu nhat — kich thuoc va bo nho. ZIP co the rat lon, va ben trong co the co file hang chuc GB. Chinh vi the ZipInputStream/ZipOutputStream la stream: chung cho phep khong can giu tat ca trong bo nho. Neu ban giai nen entry theo kieu “doc het vao ByteArray”, ban tu xoa bo y nghia cua stream.
Diem thu hai — ten entry va bao mat duong dan. Ke ca code “noi bo”, thoi quen vo tu lam File(outDir, entry.name) doi khi dan den nhung cau chuyen rat kho chiu. Trong bai nay ta da dua ra cach thuc te don gian: canonicalize duong dan va dam bao file dich van nam trong outDir.
5. Loi thuong gap khi lam viec voi ZIP
Loi #1: quen closeEntry() khi ghi hoac doc.
ZIP la dinh dang cac entry noi tiep nhau, va ranh gioi entry phai duoc danh dau ro rang. Neu ban khong dong entry khi ghi, entry sau co the bi “din” vao entry truoc; con khi doc ban co the gap hanh vi la khi chuyen giua cac phan tu. Nho quy tac: mot entry — mot putNextEntry(...) va mot closeEntry().
Loi #2: giai nen ma khong tao thu muc cha.
Entry trong archive thuong co “thu muc noi bo”, vi du docs/readme.txt. Neu ban mo ngay FileOutputStream(outFile) ma thu muc docs chua ton tai, ban se gap loi rat “oan”. Thoi quen goi outFile.parentFile?.mkdirs() truoc khi ghi giup giam nhieu buc boi.
Loi #3: viet output.write(buffer) thay vi output.write(buffer, 0, n).
Day la kinh dien cua copy theo chunk: read(buffer) tra ve n, va chi n byte dau cua buffer la hop le. Ghi ca buffer tuc la ghi them “duoi rac” (thuong la cac manh du lieu tu vong lap truoc). Voi archive bug nay rat kho chiu: ban co the tao ra ZIP “co ve thanh cong”, nhung file ben trong bi hong.
Loi #4: nghi rang entry.name la “duong dan an toan tren dia”.
Ten ben trong archive chi la mot chuoi. Neu ban chuyen thang thanh duong dan, archive co the ghi file “di bat cu dau” so voi thu muc dich. Ke ca trong vi du hoc tap, it nhat hay kiem tra toi thieu rang duong dan cuoi cung van nam trong outDir.
Loi #5: co doc ZIP “het vao bo nho” vi thay de hon.
Dung, “de” de viet kieu zip.readBytes() (hoac tuong tu) — nhung thuong bien giai nen thanh tro choi may rui ve bo nho. Y nghia cua stream va buffer la xu ly dan dan. Neu file nho thi “trong co ve on”, roi se co file lon hon, va chuong trinh bat ngo tro thanh giao trinh loi OutOfMemoryError.
GO TO FULL VERSION