Внедрение сжатия и декомпрессии формата сжатия ZIP через Java API
Кода -копия выглядит следующим образом:
пакет com.hongyuan.test;
Импорт java.io.file;
импортировать java.io.fileinputstream;
Импорт java.io.fileOutputStream;
импортировать java.io.ioexception;
импортировать java.io.inputstream;
импортировать java.io.outputstream;
Импорт java.util.enumeration;
Импорт java.util.zip.zipentry;
Импорт java.util.zip.zipfile;
импортировать java.util.zip.zipoutputstream;
открытый класс Ziptest {
public static void main (string [] args) бросает ioException {
unzip ("bootstrap.zip");
ZIP ("bootstrap_01.zip", "Bootstrap/css/bootstrap.css", "Bootstrap/css/bootstrap.min.css");
}
public static void unzip (String Filename) бросает ioException {
// Получить сжатый объект файла
Zipfile zf = new zipfile (имя файла);
// Передача записи файла
Перечисление <?
while (items.hasmoreelements ()) {
Zipentry item = item.nextelement ();
String filePath = zf.getName (). Substring (0,
zf.getName (). LastIndexof ("."))
+ File.separator + item.getName ();
File filedir = новый файл (filePath.substring (0,
filepath.lastindexof ("/"));
if (! filedir.exists ()) {
filedir.mkdirs ();
}
// Читать файл из потока
OutputStream out = new FileOutputStream (filePath);
InputStream in = zf.getInputStream (Item);
byte [] temp = новый байт [1024];
int len = 0;
while ((len = in.read (temp))> 0) {
out.write (temp, 0, len);
}
in.close ();
out.close ();
}
zf.close ();
}
public static void Zip (String FileName, String ... файлы) бросает ioException {
// Создание выходного потока сжатого файла
Zipoutputstream Zos = new ZipOutputStream (new FileOutputStream (имя файла));
для (int i = 0, size = files.length; i <size; i ++) {
// Создать сжатую сущность
Zipentry entry = new Zipentry (файлы [i] .substring (файлы [i] .lastindexof ("/")+1));
zos.putnextentry (inting);
// Содержимое выходного файла в сжатый поток
InputStream IS = new FileInputStream (files [i]);
int count = 0;
Byte [] buffer = новый байт [1024];
while ((count = is.read (buffer))> = 0) {
Zos.Write (буфер, 0, граф);
}
zos.flush ();
zos.closeentry ();
is.close ();
}
}
}