Java.util.zip.ZipInputStream класс в Java

Опубликовано: 15 Февраля, 2022

Этот класс реализует фильтр входного потока для чтения файлов в формате ZIP. Включает поддержку как сжатых, так и несжатых записей.
Конструкторы:

  • ZipInputStream (InputStream in): создает новый входной поток ZIP.
  • ZipInputStream (InputStream in, Charset charset): создает новый входной поток ZIP

Methods :

  • int available() : Returns 0 after EOF has reached for the current entry data, otherwise always return .
    Programs should not count on this method to return the actual number of bytes
    that could be read without blocking.
    Syntax :public int available()
                  throws IOException
    Overrides:
    available in class InflaterInputStream
    Returns:
    1 before EOF and 0 after EOF has reached for current entry. 
    Programs should not count on this method to return the actual number 
    of bytes that could be read without blocking.
    Throws:
    IOException 
  • void close() : Closes this input stream and releases any system resources associated with the stream.
    Syntax :public void close()
               throws IOException
    Overrides:
    close in class InflaterInputStream
    Throws:
    IOException
  • void closeEntry() : Closes the current ZIP entry and positions the stream for reading the next entry.
    Syntax :public void closeEntry()
                    throws IOException
    Throws:
    ZipException 
    IOException 
  • protected ZipEntry createZipEntry(String name) : Creates a new ZipEntry object for the specified entry name.
    Syntax :protected ZipEntry createZipEntry(String name)
    Parameters:
    name - the ZIP file entry name
    Returns:
    the ZipEntry just created
  • ZipEntry getNextEntry() : Reads the next ZIP file entry and positions the stream at the beginning of the entry data.
    Syntax :public ZipEntry getNextEntry()
                          throws IOException
    Returns:
    the next ZIP file entry, or null if there are no more entries
    Throws:
    ZipException 
    IOException 
  • int read(byte[] b, int off, int len) : 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.
    Syntax :public int read(byte[] b,
           int off,
           int len)
             throws IOException
    Parameters:
    b - the buffer into which the data is read
    off - the start offset in the destination array b
    len - the maximum number of bytes read
    Returns:
    the actual number of bytes read, or -1 if the end of the entry is reached
    Throws:
    NullPointerException 
    IndexOutOfBoundsException 
    ZipException 
    IOException
  • long skip(long n) : Skips specified number of bytes in the current ZIP entry.
    Syntax :public long skip(long n)
              throws IOException
    Parameters:
    n - the number of bytes to skip
    Returns:
    the actual number of bytes skipped
    Throws:
    ZipException
    IOException
    IllegalArgumentException 
//Java program demonstrating ZipInputStream methods
  
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
class ZipInputStreamDemo extends ZipInputStream
{
    public ZipInputStreamDemo(InputStream in) 
    {
        super(in);
    }
  
    public static void main(String[] args) throws IOException
    {
        FileInputStream fis = new FileInputStream("Awesome CV.zip");
        ZipInputStream zis = new JarInputStream(fis);
        ZipInputStreamDemo obj = new ZipInputStreamDemo(zis);
  
        //illustrating createZipEntry()
        ZipEntry ze = obj.createZipEntry("ZipEntry");
        System.out.println(ze.getName());
  
        //illustrating getNextEntry()
        ZipEntry je = zis.getNextEntry();
        System.out.println(je.getName());
  
        //illustrating skip() method
        zis.skip(3);
  
        //illustrating closeEntry() method
        zis.closeEntry();
        zis.getNextEntry();
        byte b[] = new byte[10];
  
        //illustrating available() method
        //Reads up to byte.length bytes of data from this input stream
        if(zis.available() == 1)
            zis.read(b);
        System.out.println(Arrays.toString(b));
  
        //closing the stream
        zis.close();
    }
}

Выход :

 ZipEntry
awesome-cv.cls
[35, 32, 65, 119, 101, 115, 111, 109, 101, 32]

Автор статьи - Нишант Шарма . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью с помощью provide.geeksforgeeks.org или отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .