Java.util.jar.JarInputStream класс в Java

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

Класс JarInputStream используется для чтения содержимого файла JAR из любого входного потока. Он расширяет класс java.util.zip.ZipInputStream за счет поддержки чтения необязательной записи манифеста. Манифест может использоваться для хранения метаинформации о файле JAR и его записях.
Конструкторы

  • JarInputStream (InputStream in): создает новый JarInputStream и читает необязательный манифест.
  • JarInputStream (InputStream in, boolean verify): создает новый JarInputStream и читает необязательный манифест.

Methods:

  • protected ZipEntry createZipEntry(String name) : Creates a new JarEntry (ZipEntry) for the specified JAR file entry name.The manifest attributes of the specified JAR file entry name will be copied to the new JarEntry.
  • Manifest getManifest() : Returns the Manifest for this JAR file, or null if none.
    Syntax :public Manifest getManifest()
    Returns:
    the Manifest for this JAR file, or null if none.
  • ZipEntry getNextEntry() : Reads the next ZIP file entry and positions the stream at the beginning of the entry data.If verification has been enabled, any invalid signature detected while positioning the stream for the next entry will result in an exception.
    Syntax :public ZipEntry getNextEntry()
                          throws IOException
    Overrides:
    getNextEntry in class ZipInputStream
    Returns:
    the next ZIP file entry, or null if there are no more entries
    Throws:
    ZipException 
    IOException 
    SecurityException
  • JarEntry getNextJarEntry() : Reads the next JAR file entry and positions the stream at the beginning of the entry data.If verification has been enabled, any invalid signature detected while positioning the stream for the next entry will result in an exception.
    Syntax :public JarEntry getNextJarEntry()
                             throws IOException
    Returns:
    the next JAR file entry, or null if there are no more entries
    Throws:
    ZipException 
    IOException 
    SecurityException
  • int read(byte[] b, int off, int len) : Reads from the current JAR file 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. If verification has been enabled, any invalid signature on the current entry will be reported at some point before the end of the entry is reached.
    Syntax :public int read(byte[] b,
           int off,
           int len)
             throws IOException
    Overrides:
    read in class ZipInputStream
    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 to read
    Returns:
    the actual number of bytes read, or -1 if the end of the entry is reached
    Throws:
    NullPointerException 
    IndexOutOfBoundsException 
    ZipException 
    IOException 
    SecurityException 
//Java program demonstrating JarInputStream 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;
  
class JarInputStreamDemo extends JarInputStream
{
  
    public JarInputStreamDemo(InputStream in) throws IOException 
    {
        super(in);
    }
    public static void main(String[] args) throws IOException
    {
        FileInputStream is = new FileInputStream("codechecker.jar");
        JarInputStream jis = new JarInputStream(is);
        JarInputStreamDemo obj=new JarInputStreamDemo(jis);
  
        //illustrating createZipEntry() method
        ZipEntry ze1=obj.createZipEntry("ZipEntry");
        System.out.println(ze1.getName());
  
        //illustrating getNextEntry() method
        ZipEntry ze=jis.getNextEntry();
        System.out.println(ze.getName());
  
        //illustrating getManifest();
        System.out.println(jis.getManifest());
  
        // Reading from the current JAR file entry
        // into an array of 10 bytes
        byte b[] = new byte[10];
  
        //illustrating getNextJarEntry()
        //illustrating read(byte b[],int off,int length)
        while(jis.getNextJarEntry()!= null)
            jis.read(b);
        System.out.print(Arrays.toString(b));
  
        //closing the stream
        jis.close();
    }
}

Выход :

 Zipentry
Внимание-64.png
java.util.jar.Manifest@513ee0c5
[-119, 80, 78, 71, 13, 10, 26, 10, 0, 0]

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

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

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