Java zip file entries

Содержание
  1. Class ZipInputStream
  2. Field Summary
  3. Fields declared in class java.util.zip.InflaterInputStream
  4. Fields declared in class java.io.FilterInputStream
  5. Constructor Summary
  6. Method Summary
  7. Methods declared in class java.util.zip.InflaterInputStream
  8. Methods declared in class java.io.FilterInputStream
  9. Methods declared in class java.io.InputStream
  10. Methods declared in class java.lang.Object
  11. Field Details
  12. LOCSIG
  13. EXTSIG
  14. CENSIG
  15. ENDSIG
  16. LOCHDR
  17. EXTHDR
  18. CENHDR
  19. ENDHDR
  20. LOCVER
  21. LOCFLG
  22. LOCHOW
  23. LOCTIM
  24. LOCCRC
  25. LOCSIZ
  26. LOCLEN
  27. LOCNAM
  28. LOCEXT
  29. EXTCRC
  30. EXTSIZ
  31. EXTLEN
  32. CENVEM
  33. CENVER
  34. CENFLG
  35. CENHOW
  36. CENTIM
  37. CENCRC
  38. CENSIZ
  39. CENLEN
  40. CENNAM
  41. CENEXT
  42. CENCOM
  43. CENDSK
  44. CENATT
  45. CENATX
  46. CENOFF
  47. ENDSUB
  48. ENDTOT
  49. ENDSIZ
  50. ENDOFF
  51. ENDCOM
  52. Constructor Details
  53. ZipInputStream
  54. ZipInputStream
  55. Method Details
  56. getNextEntry
  57. closeEntry
  58. available
  59. read
  60. skip
  61. close
  62. createZipEntry
  63. Class ZipInputStream
  64. Reading Zip File Entries
  65. Field Summary
  66. Fields declared in class java.util.zip.InflaterInputStream
  67. Fields declared in class java.io.FilterInputStream
  68. Constructor Summary
  69. Method Summary
  70. Methods declared in class java.util.zip.InflaterInputStream
  71. Methods declared in class java.io.FilterInputStream
  72. Methods declared in class java.io.InputStream
  73. Methods declared in class java.lang.Object
  74. Field Details
  75. LOCSIG
  76. EXTSIG
  77. CENSIG
  78. ENDSIG
  79. LOCHDR
  80. EXTHDR
  81. CENHDR
  82. ENDHDR
  83. LOCVER
  84. LOCFLG
  85. LOCHOW
  86. LOCTIM
  87. LOCCRC
  88. LOCSIZ
  89. LOCLEN
  90. LOCNAM
  91. LOCEXT
  92. EXTCRC
  93. EXTSIZ
  94. EXTLEN
  95. CENVEM
  96. CENVER
  97. CENFLG
  98. CENHOW
  99. CENTIM
  100. CENCRC
  101. CENSIZ
  102. CENLEN
  103. CENNAM
  104. CENEXT
  105. CENCOM
  106. CENDSK
  107. CENATT
  108. CENATX
  109. CENOFF
  110. ENDSUB
  111. ENDTOT
  112. ENDSIZ
  113. ENDOFF
  114. ENDCOM
  115. Constructor Details
  116. ZipInputStream
  117. ZipInputStream
  118. Method Details
  119. getNextEntry
  120. closeEntry
  121. available
  122. read
  123. readAllBytes
  124. readNBytes
  125. readNBytes
  126. skipNBytes
  127. transferTo
  128. read
  129. skip
  130. close
  131. createZipEntry
  132. Java zip file entries
  133. ZipOutputStream. Запись архивов
  134. Чтение архивов. 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.

Читайте также:  Gmuzbekistan uz proslejivanie zayavki html

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».

Источник

Оцените статью