אנחנו נסתכל היום על דוגמא לקובץ זיפ ב-Java. אנו גם נדחוס תיקייה וניצור קובץ זיפ באמצעות תוכנית Java.
Java ZIP
java.util.zip.ZipOutputStream
ניתן להשתמש בו כדי לדחוס קובץ לתבנית ZIP. מאחר וקובץ ZIP יכול לכלול מספר רב של רשומות, ZipOutputStream משתמש ב־java.util.zip.ZipEntry
כדי לייצג רשומה בקובץ ZIP.
קובץ ZIP ב-Java
יצירת ארכיון זיפ עבור קובץ יחיד היא קלה מאוד, אנו צריכים ליצור אובייקט ZipOutputStream מתוך אובייקט FileOutputStream של קובץ היעד. אחר כך אנו מוסיפים רשומה חדשה ל-ZipOutputStream ומשתמשים ב-FileInputStream כדי לקרוא את קובץ המקור לאובייקט ZipOutputStream. לאחר שכתבנו את המידע, אנו צריכים לסגור את ZipEntry ולשחרר את כל המשאבים.
תיקיית זיפ ב-Java
דחיסת ספרייה דורשת קצת תכנון, תחילה עלינו לקבל את רשימת הקבצים עם נתיב מוחלט. לאחר מכן נעבוד על כל קובץ בנפרד. עלינו להוסיף ZipEntry עבור כל קובץ ולהשתמש ב־FileInputStream כדי לקרוא את תוכן הקובץ המקורי ל־ZipEntry המתאים לקובץ זה.
דוגמת Zip ב־Java
הנה התוכנית ב־Java שמציגה איך לדחוס קובץ יחיד או לדחוס תיקייה ב־Java.
package com.journaldev.files;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
List filesListInDir = new ArrayList();
public static void main(String[] args) {
File file = new File("/Users/pankaj/sitemap.xml");
String zipFileName = "/Users/pankaj/sitemap.zip";
File dir = new File("/Users/pankaj/tmp");
String zipDirName = "/Users/pankaj/tmp.zip";
zipSingleFile(file, zipFileName);
ZipFiles zipFiles = new ZipFiles();
zipFiles.zipDirectory(dir, zipDirName);
}
/**
* This method zips the directory
* @param dir
* @param zipDirName
*/
private void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//כעת נדחוס את הקבצים אחד אחרי השני
//יצירת ZipOutputStream לכתיבה לקובץ ה־zip
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String filePath : filesListInDir){
System.out.println("Zipping "+filePath);
//עבור ZipEntry עלינו לשמור רק נתיב יחסי של הקובץ, לכן השתמשנו ב־substring על הנתיב המוחלט
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
zos.putNextEntry(ze);
//קריאה של הקובץ וכתיבה ל־ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method populates all the files in a directory to a List
* @param dir
* @throws IOException
*/
private void populateFilesList(File dir) throws IOException {
File[] files = dir.listFiles();
for(File file : files){
if(file.isFile()) filesListInDir.add(file.getAbsolutePath());
else populateFilesList(file);
}
}
/**
* This method compresses the single file to zip format
* @param file
* @param zipFileName
*/
private static void zipSingleFile(File file, String zipFileName) {
try {
//יצירת ZipOutputStream לכתיבה לקובץ ה־zip
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
//הוספת Zip Entry חדש ל־ZipOutputStream
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
//קריאה של הקובץ וכתיבה ל־ZipOutputStream
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
//סגירת ה־zip entry כדי לכתוב לקובץ ה־zip
zos.closeEntry();
//סגירת משאבים
zos.close();
fis.close();
fos.close();
System.out.println(file.getCanonicalPath()+" is zipped to "+zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
פלט של דוגמת דחיסה ב־Java מוצג למעלה:
/Users/pankaj/sitemap.xml is zipped to /Users/pankaj/sitemap.zip
Zipping /Users/pankaj/tmp/.DS_Store
Zipping /Users/pankaj/tmp/data/data.dat
Zipping /Users/pankaj/tmp/data/data.xml
Zipping /Users/pankaj/tmp/data/xmls/project.xml
Zipping /Users/pankaj/tmp/data/xmls/web.xml
Zipping /Users/pankaj/tmp/data.Xml
Zipping /Users/pankaj/tmp/DB.xml
Zipping /Users/pankaj/tmp/item.XML
Zipping /Users/pankaj/tmp/item.xsd
Zipping /Users/pankaj/tmp/ms/data.txt
Zipping /Users/pankaj/tmp/ms/project.doc
שים לב שבזמן שאני מסומן קבצים לדחיסה בתיקייה, אני מדפיס את הנתיב המוחלט. אך בעת הוספת קובץ לדחיסה, אני משתמש בנתיב יחסי מהתיקייה כך שכאשר נפתח אותו, ייווצרו אותם מבנה תיקיות. זהו כל מה שיש לדוגמת דחיסה ב־Java.
Source:
https://www.digitalocean.com/community/tutorials/java-zip-file-folder-example