- Class ZipInputStream
- Field Summary
- Fields declared in class java.util.zip.InflaterInputStream
- Fields declared in class java.io.FilterInputStream
- Constructor Summary
- Method Summary
- Methods declared in class java.util.zip.InflaterInputStream
- Methods declared in class java.io.FilterInputStream
- Methods declared in class java.io.InputStream
- Methods declared in class java.lang.Object
- Field Details
- LOCSIG
- EXTSIG
- CENSIG
- ENDSIG
- LOCHDR
- EXTHDR
- CENHDR
- ENDHDR
- LOCVER
- LOCFLG
- LOCHOW
- LOCTIM
- LOCCRC
- LOCSIZ
- LOCLEN
- LOCNAM
- LOCEXT
- EXTCRC
- EXTSIZ
- EXTLEN
- CENVEM
- CENVER
- CENFLG
- CENHOW
- CENTIM
- CENCRC
- CENSIZ
- CENLEN
- CENNAM
- CENEXT
- CENCOM
- CENDSK
- CENATT
- CENATX
- CENOFF
- ENDSUB
- ENDTOT
- ENDSIZ
- ENDOFF
- ENDCOM
- Constructor Details
- ZipInputStream
- ZipInputStream
- Method Details
- getNextEntry
- closeEntry
- available
- read
- skip
- close
- createZipEntry
- Class ZipInputStream
- Reading Zip File Entries
- Field Summary
- Fields declared in class java.util.zip.InflaterInputStream
- Fields declared in class java.io.FilterInputStream
- Constructor Summary
- Method Summary
- Methods declared in class java.util.zip.InflaterInputStream
- Methods declared in class java.io.FilterInputStream
- Methods declared in class java.io.InputStream
- Methods declared in class java.lang.Object
- Field Details
- LOCSIG
- EXTSIG
- CENSIG
- ENDSIG
- LOCHDR
- EXTHDR
- CENHDR
- ENDHDR
- LOCVER
- LOCFLG
- LOCHOW
- LOCTIM
- LOCCRC
- LOCSIZ
- LOCLEN
- LOCNAM
- LOCEXT
- EXTCRC
- EXTSIZ
- EXTLEN
- CENVEM
- CENVER
- CENFLG
- CENHOW
- CENTIM
- CENCRC
- CENSIZ
- CENLEN
- CENNAM
- CENEXT
- CENCOM
- CENDSK
- CENATT
- CENATX
- CENOFF
- ENDSUB
- ENDTOT
- ENDSIZ
- ENDOFF
- ENDCOM
- Constructor Details
- ZipInputStream
- ZipInputStream
- Method Details
- getNextEntry
- closeEntry
- available
- read
- readAllBytes
- readNBytes
- readNBytes
- skipNBytes
- transferTo
- read
- skip
- close
- createZipEntry
- Java zip file entries
- ZipOutputStream. Запись архивов
- Чтение архивов. ZipInputStream
Class ZipInputStream
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.
Field Summary
Fields declared in class java.util.zip.InflaterInputStream
Fields declared in class java.io.FilterInputStream
Constructor Summary
Method Summary
Methods declared in class java.util.zip.InflaterInputStream
Methods declared in class java.io.FilterInputStream
Methods declared in class java.io.InputStream
Methods declared in class java.lang.Object
Field Details
LOCSIG
EXTSIG
CENSIG
ENDSIG
LOCHDR
EXTHDR
CENHDR
ENDHDR
LOCVER
LOCFLG
LOCHOW
LOCTIM
LOCCRC
LOCSIZ
LOCLEN
LOCNAM
LOCEXT
EXTCRC
EXTSIZ
EXTLEN
CENVEM
CENVER
CENFLG
CENHOW
CENTIM
CENCRC
CENSIZ
CENLEN
CENNAM
CENEXT
CENCOM
CENDSK
CENATT
CENATX
CENOFF
ENDSUB
ENDTOT
ENDSIZ
ENDOFF
ENDCOM
Constructor Details
ZipInputStream
ZipInputStream
Method Details
getNextEntry
closeEntry
available
Returns 0 after EOF has reached for the current entry data, otherwise always return 1. Programs should not count on this method to return the actual number of bytes that could be read without blocking.
read
Reads from the current ZIP entry into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.
skip
close
createZipEntry
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Class ZipInputStream
An input stream for reading compressed and uncompressed ZIP file entries from a stream of bytes in the ZIP file format.
Reading Zip File Entries
The getNextEntry() method is used to read the next ZIP file entry (Local file (LOC) header record in the ZIP format) and position the stream at the entry’s file data. The file data may read using one of the ZipInputStream read methods such as read or readAllBytes() . For example:
Path jar = Path.of("foo.jar"); try (InputStream is = Files.newInputStream(jar); ZipInputStream zis = new ZipInputStream(is)) < ZipEntry ze; while((ze= zis.getNextEntry()) != null) < var bytes = zis.readAllBytes(); System.out.printf("Entry: %s, bytes read: %s%n", ze.getName(), bytes.length); >>
Field Summary
Fields declared in class java.util.zip.InflaterInputStream
Fields declared in class java.io.FilterInputStream
Constructor Summary
Method Summary
Returns 0 when end of stream is detected for the current ZIP entry or closeEntry() has been called on the current ZIP entry, otherwise returns 1.
Reads the requested number of bytes from the input stream into the given byte array for the current ZIP entry returning the number of inflated bytes.
Reads the requested number of bytes from the input stream into the given byte array for the current ZIP entry returning the number of inflated bytes.
Reads all bytes from this input stream for the current ZIP entry and writes the bytes to the given output stream in the order that they are read.
Methods declared in class java.util.zip.InflaterInputStream
Methods declared in class java.io.FilterInputStream
Methods declared in class java.io.InputStream
Methods declared in class java.lang.Object
Field Details
LOCSIG
EXTSIG
CENSIG
ENDSIG
LOCHDR
EXTHDR
CENHDR
ENDHDR
LOCVER
LOCFLG
LOCHOW
LOCTIM
LOCCRC
LOCSIZ
LOCLEN
LOCNAM
LOCEXT
EXTCRC
EXTSIZ
EXTLEN
CENVEM
CENVER
CENFLG
CENHOW
CENTIM
CENCRC
CENSIZ
CENLEN
CENNAM
CENEXT
CENCOM
CENDSK
CENATT
CENATX
CENOFF
ENDSUB
ENDTOT
ENDSIZ
ENDOFF
ENDCOM
Constructor Details
ZipInputStream
ZipInputStream
Method Details
getNextEntry
closeEntry
available
Returns 0 when end of stream is detected for the current ZIP entry or closeEntry() has been called on the current ZIP entry, otherwise returns 1. Programs should not count on this method to return the actual number of bytes that could be read without blocking.
read
Reads the next byte of data from the input stream for the current ZIP entry. This method will block until enough input is available for decompression.
readAllBytes
Reads all remaining bytes from the input stream for the current ZIP entry. This method blocks until all remaining bytes have been read and end of stream is detected, or an exception is thrown. This method does not close the input stream. When this stream reaches end of stream, further invocations of this method will return an empty byte array. Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading input streams with large amounts of data. If an I/O error occurs reading from the input stream, then it may do so after some, but not all, bytes have been read. Consequently, the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the stream be promptly closed if an I/O error occurs.
readNBytes
Reads up to a specified number of bytes from the input stream for the current ZIP entry. This method blocks until the requested number of bytes has been read, end of stream is detected, or an exception is thrown. This method does not close the input stream. The length of the returned array equals the number of bytes read from the stream. If len is zero, then no bytes are read and an empty byte array is returned. Otherwise, up to len bytes are read from the stream. Fewer than len bytes may be read if end of stream is encountered. When this stream reaches end of stream, further invocations of this method will return an empty byte array. Note that this method is intended for simple cases where it is convenient to read the specified number of bytes into a byte array. The total amount of memory allocated by this method is proportional to the number of bytes read from the stream which is bounded by len . Therefore, the method may be safely called with very large values of len provided sufficient memory is available. If an I/O error occurs reading from the input stream, then it may do so after some, but not all, bytes have been read. Consequently, the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the stream be promptly closed if an I/O error occurs.
readNBytes
Reads the requested number of bytes from the input stream into the given byte array for the current ZIP entry returning the number of inflated bytes. This method blocks until len bytes of input data have been read, end of stream is detected, or an exception is thrown. The number of bytes actually read, possibly zero, is returned. This method does not close the input stream. In the case where end of stream is reached before len bytes have been read, then the actual number of bytes read will be returned. When this stream reaches end of stream, further invocations of this method will return zero. If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read up to len bytes. The first byte read is stored into element b[off] , the next one in to b[off+1] , and so on. The number of bytes read is, at most, equal to len . Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+ k -1] , leaving elements b[off+ k ] through b[off+len-1] unaffected. If an I/O error occurs reading from the input stream, then it may do so after some, but not all, bytes of b have been updated with data from the input stream. Consequently, the input stream and b may be in an inconsistent state. It is strongly recommended that the stream be promptly closed if an I/O error occurs.
skipNBytes
Skips over and discards exactly n bytes of data from this input stream for the current ZIP entry. If n is zero, then no bytes are skipped. If n is negative, then no bytes are skipped. Subclasses may handle the negative value differently. This method blocks until the requested number of bytes has been skipped, end of file is reached, or an exception is thrown. If end of stream is reached before the stream is at the desired position, then an EOFException is thrown. If an I/O error occurs, then the input stream may be in an inconsistent state. It is strongly recommended that the stream be promptly closed if an I/O error occurs.
transferTo
Reads all bytes from this input stream for the current ZIP entry and writes the bytes to the given output stream in the order that they are read. On return, this input stream will be at end of stream. This method does not close either stream. This method may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted during the transfer, is highly input and output stream specific, and therefore not specified. If an I/O error occurs reading from the input stream or writing to the output stream, then it may do so after some bytes have been read or written. Consequently, the input stream may not be at end of stream and one, or both, streams may be in an inconsistent state. It is strongly recommended that both streams be promptly closed if an I/O error occurs.
read
Reads the requested number of bytes from the input stream into the given byte array for the current ZIP entry returning the number of inflated bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned. If the current entry is compressed and this method returns a nonzero integer n then buf[off] through buf[off+ n -1] contain the uncompressed data. The content of elements buf[off+ n ] through buf[off+ len -1] is undefined, contrary to the specification of the InputStream superclass, so an implementation is free to modify these elements during the inflate operation. If this method returns -1 or throws an exception then the content of buf[off] through buf[off+ len -1] is undefined.
skip
close
createZipEntry
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Java zip file entries
Кроме общего функционала для работы с файлами Java предоставляет функциональность для работы с таким видом файлов как zip-архивы. Для этого в пакете java.util.zip определены два класса — ZipInputStream и ZipOutputStream
ZipOutputStream. Запись архивов
Для создания архива используется класс ZipOutputStream. Для создания объекта ZipOutputStream в его конструктор передается поток вывода:
ZipOutputStream(OutputStream out)
Для записи файлов в архив для каждого файла создается объект ZipEntry , в конструктор которого передается имя архивируемого файла. А чтобы добавить каждый объект ZipEntry в архив, применяется метод putNextEntry() .
import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < String filename = "notes.txt"; try(ZipOutputStream zout = new ZipOutputStream(new FileOutputStream("output.zip")); FileInputStream fis= new FileInputStream(filename);) < ZipEntry entry1=new ZipEntry("notes.txt"); zout.putNextEntry(entry1); // считываем содержимое файла в массив byte byte[] buffer = new byte[fis.available()]; fis.read(buffer); // добавляем содержимое к архиву zout.write(buffer); // закрываем текущую запись для новой записи zout.closeEntry(); >catch(Exception ex) < System.out.println(ex.getMessage()); >> >
После добавления объекта ZipEntry в поток нам также надо добавить в него и содержимое файла. Для этого используется метод write, записывающий в поток массив байтов: zout.write(buffer); . В конце надо закрыть ZipEntry с помощью метода closeEntry() . После этого можно добавлять в архив новые файлы — в этом случае все вышеописанные действия для каждого нового файла повторяются.
Чтение архивов. ZipInputStream
Для чтения архивов применяется класс ZipInputStream . В конструкторе он принимает поток, указывающий на zip-архив:
ZipInputStream(InputStream in)
Для считывания файлов из архива ZipInputStream использует метод getNextEntry() , который возвращает объект ZipEntry . Объект ZipEntry представляет отдельную запись в zip-архиве. Например, считаем какой-нибудь архив:
import java.io.*; import java.util.zip.*; public class Program < public static void main(String[] args) < try(ZipInputStream zin = new ZipInputStream(new FileInputStream("output.zip"))) < ZipEntry entry; String name; while((entry=zin.getNextEntry())!=null)< name = entry.getName(); // получим название файла System.out.printf("File name: %s \n", name); // распаковка FileOutputStream fout = new FileOutputStream("new" + name); for (int c = zin.read(); c != -1; c = zin.read()) < fout.write(c); >fout.flush(); zin.closeEntry(); fout.close(); > > catch(Exception ex) < System.out.println(ex.getMessage()); >> >
ZipInputStream в конструкторе получает ссылку на поток ввода. И затем в цикле выводятся все файлы и их размер в байтах, которые находятся в данном архиве.
Затем данные извлекаются из архива и сохраняются в новые файлы, которые находятся в той же папке и которые начинаются с «new».