Java Zip - Quick Guide


Advertisements


java.util.zip - Adler32

Introduction

The java.util.zip.Adler32 class is a class that can be used to compute the Adler-32 checksum of a data stream. An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed much faster.

Class declaration

Following is the declaration for java.util.zip.Adler32 class −

public class Adler32
   extends Object
      implements Checksum

Constructors

S.N. Constructor & Description
1 Adler32()

Creates a new Adler32 object.

Class methods

S.N. Method & Description
1 long getValue()

Returns the checksum value.

2 void reset()

Resets the checksum to initial value.

3 void update(byte[] b)

Updates the checksum with the specified array of bytes.

4 void update(byte[] b, int off, int len)

Updates the checksum with the specified array of bytes.

5 void update(int b)

Updates the checksum with the specified byte (the low eight bits of the argument b).

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.util.zip.Adler32.getValue() Method Example

Description

The java.util.zip.Adler32.getValue() method returns the checksum value.

Declaration

Following is the declaration for java.util.zip.Adler32.getValue() method.

public long getValue()

Returns

the current checksum value.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.Adler32.getValue() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Adler32Demo {

   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      byte[] buffer = new byte[1024];

      try {
         FileOutputStream fout = new FileOutputStream(TARGET_FILE);
         CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
         ZipOutputStream zout = new ZipOutputStream(checksum);

         FileInputStream fin = new FileInputStream(SOURCE_FILE);
         zout.putNextEntry(new ZipEntry(SOURCE_FILE));
         int length;
         while((length = fin.read(buffer)) > 0) {
            zout.write(buffer, 0, length);
         }

         zout.closeEntry();
         fin.close();
         zout.close();
         System.out.println("Zip file generated!");
         System.out.println("Adler32 Checksum is : " + checksum.getChecksum().getValue());
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Zip file generated!
Adler32 Checksum is : 504112553

java.util.zip.Adler32.reset() Method Example

Description

The java.util.zip.Adler32.reset() method resets the checksum to initial value.

Declaration

Following is the declaration for java.util.zip.Adler32.reset() method.

public void reset()

Returns

the current checksum value.

Example

The following example shows the usage of java.util.zip.Adler32.reset() method.

package com.tutorialspoint;

import java.util.zip.Adler32;
import java.util.zip.Checksum;

public class Adler32Demo {

   public static void main(String[] args) {
      String message = "Welcome to Tutorialspoint.com";
      byte bytes[] = message.getBytes();
      Checksum checksum = new Adler32();
      checksum.reset();       
      checksum.update(bytes,0,bytes.length);
      long checksumValue = checksum.getValue();
      System.out.println("Adler32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

Adler32 checksum :2799700814

java.util.zip.Adler32.update(byte[] b) Method Example

Description

The java.util.zip.Adler32.update(byte[] b) method updates the checksum with the specified array of bytes.

Declaration

Following is the declaration for java.util.zip.Adler32.update(byte[] b) method.

public void update(byte[] b)

Parameters

  • b - the byte array to update the checksum with.

Example

The following example shows the usage of java.util.zip.Adler32.update(byte[] b) method.

package com.tutorialspoint;

import java.util.zip.Adler32;

public class Adler32Demo {

   public static void main(String[] args) {
      String message = "Welcome to Tutorialspoint.com";
      byte bytes[] = message.getBytes();

      Adler32 checksum = new Adler32();
      checksum.reset();       

      checksum.update(bytes);
      long checksumValue = checksum.getValue();

      System.out.println("Adler32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

Adler32 checksum :2799700814

java.util.zip.Adler32.update(byte[] b, int off, int len) Method Example

Description

The java.util.zip.Adler32.update(byte[] b, int off, int len) method updates the checksum with the specified array of bytes.

Declaration

Following is the declaration for java.util.zip.Adler32.update(byte[] b, int off, int len) method.

public void update(byte[] b, int off, int len)

Parameters

  • b - the byte array to update the checksum with.

  • off - the start offset of the data.

  • len - the number of bytes to use for the update.

Example

The following example shows the usage of java.util.zip.Adler32.update(byte[] b) method.

package com.tutorialspoint;

import java.util.zip.Adler32;
import java.util.zip.Checksum;

public class Adler32Demo {

   public static void main(String[] args) {
      String message = "Welcome to Tutorialspoint.com";
      byte bytes[] = message.getBytes();
      Checksum checksum = new Adler32();
      checksum.reset();       
      checksum.update(bytes,0,bytes.length);
      long checksumValue = checksum.getValue();
      System.out.println("Adler32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

Adler32 checksum :2799700814

java.util.zip.Adler32.update(int b) Method Example

Description

The java.util.zip.Adler32.update(int b) method updates the checksum with the specified byte (the low eight bits of the argument b).

Declaration

Following is the declaration for java.util.zip.Adler32.update(int b) method.

public void update(int b)

Parameters

  • b - the byte to update the checksum with.

Example

The following example shows the usage of java.util.zip.Adler32.update(byte[] b) method.

package com.tutorialspoint;

import java.util.zip.Adler32;
import java.util.zip.Checksum;

public class Adler32Demo {
   public static void main(String[] args) {
      int bytes = 55;

      Checksum checksum = new Adler32();
      checksum.reset();       

      checksum.update(bytes);
      long checksumValue = checksum.getValue();

      System.out.println("Adler32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

Adler32 checksum :3670072

java.util.zip - CheckedInputStream

Introduction

The java.util.zip.CheckedInputStream class is an input stream that also maintains a checksum of the data being read. The checksum can then be used to verify the integrity of the input data.

Class declaration

Following is the declaration for java.util.zip.CheckedInputStream class −

public class CheckedInputStream
   extends FilterInputStream

Constructors

S.N. Constructor & Description
1 CheckedInputStream(InputStream in, Checksum cksum)

Creates an input stream using the specified Checksum.

Class methods

S.N. Method & Description
1 Checksum getChecksum()

Returns the Checksum for this input stream.

2 int read()

Reads a byte.

3 int read(byte[] buf, int off, int len)

Reads into an array of bytes.

4 long skip(long n)

Skips specified number of bytes of input.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterInputStream
  • java.lang.Object

java.util.zip.CheckedInputStream.getChecksum() Method Example

Description

The java.util.zip.CheckedInputStream.getChecksum() method returns the Checksum for this input stream.

Declaration

Following is the declaration for java.util.zip.CheckedInputStream.getChecksum() method.

public Checksum getChecksum()

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedInputStream.getChecksum() method.

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class CheckedInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
 
         createZipFile();
 
         FileInputStream fin1= new FileInputStream(TARGET_FILE);
         CheckedInputStream checksum1 = new CheckedInputStream(fin1, new Adler32());
         ZipInputStream zin = new ZipInputStream(checksum1);

         BufferedInputStream bis = new BufferedInputStream(zin);
         ZipEntry ze;
         while ((ze = zin.getNextEntry()) != null) {
            System.out.println("Reading file " + ze);
            int x;
            while ((x = bis.read()) != -1)
               System.out.write(x);
         }
         System.out.println("Checksum: " + checksum1.getChecksum().getValue());
         bis.close();       
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
   
   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      zout.putNextEntry(new ZipEntry(SOURCE_FILE));
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }
}

Let us compile and run the above program, this will produce the following result −

Reading file D:\test\Hello.txt
This is an example page.
Checksum: 1400120861

java.util.zip.CheckedInputStream.read() Method Example

Description

The java.util.zip.CheckedInputStream.read() method returns the Checksum for this input stream.

Declaration

Following is the declaration for java.util.zip.CheckedInputStream.read() method.

public int read()
   throws IOException

Returns

the byte read, or -1 if the end of the stream is reached.

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedInputStream.read() method.

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class CheckedInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
 
         createZipFile();
 
         FileInputStream fin= new FileInputStream(TARGET_FILE);
         CheckedInputStream checksum = new CheckedInputStream(fin, new Adler32());
         while(checksum.read() >= 0){        
 
         } 

         System.out.println("Checksum: " + checksum.getChecksum().getValue());      
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
   
   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      zout.putNextEntry(new ZipEntry(SOURCE_FILE));
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }
}

Let us compile and run the above program, this will produce the following result −

Checksum: 1400120861

java.util.zip.CheckedInputStream.read(byte[] buf, int off, int len) Method Example

Description

The java.util.zip.CheckedInputStream.read(byte[] buf, int off, int len) method reads 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.

Declaration

Following is the declaration for java.util.zip.CheckedInputStream.read(byte[] buf, int off, int len) method.

public int read(byte[] buf, int off, int len)
   throws IOException

Parameters

  • buf - 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 stream is reached.

Exceptions

  • NullPointerException - If buf is null.

  • IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than buf.length - off.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedInputStream.read(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class CheckedInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
 
         createZipFile();
 
         FileInputStream fin= new FileInputStream(TARGET_FILE);
         CheckedInputStream checksum = new CheckedInputStream(fin, new Adler32());
byte[] buffer = new byte[1024];
         while(checksum.read(buffer, 0, buffer.length) >= 0){        
 
      } 

         System.out.println("Checksum: " + checksum.getChecksum().getValue());      
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
   
   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      zout.putNextEntry(new ZipEntry(SOURCE_FILE));
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }
}

Let us compile and run the above program, this will produce the following result −

Checksum: 1400120861

java.util.zip.CheckedInputStream.skip(long n) Method Example

Description

The java.util.zip.CheckedInputStream.skip(long n) method skips specified number of bytes of input.

Declaration

Following is the declaration for java.util.zip.CheckedInputStream.skip(long n) method.

public long skip(long n)
   throws IOException

Parameters

  • n - the number of bytes to skip.

Returns

the actual number of bytes skipped.

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedInputStream.skip(long n) method.

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class CheckedInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
 
         createZipFile();
 
         FileInputStream fin= new FileInputStream(TARGET_FILE);
         CheckedInputStream checksum = new CheckedInputStream(fin, new Adler32());
byte[] buffer = new byte[1024];
         checksum.skip(buffer.length);

         System.out.println("Checksum: " + checksum.getChecksum().getValue());      
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
   
   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      zout.putNextEntry(new ZipEntry(SOURCE_FILE));
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }
}

Let us compile and run the above program, this will produce the following result −

Checksum: 1400120861

java.util.zip - CheckedOutputStream

Introduction

The java.util.zip.CheckedOutputStream class is an output stream that also maintains a checksum of the data being written. The checksum can then be used to verify the integrity of the output data.

Class declaration

Following is the declaration for java.util.zip.CheckedOutputStream class −

public class CheckedOutputStream
   extends FilterOutputStream

Constructors

S.N. Constructor & Description
1 CheckedOutputStream(OutputStream out, Checksum cksum)

Creates an output stream with the specified Checksum.

Class methods

S.N. Method & Description
1 Checksum getChecksum()

Returns the Checksum for this output stream.

2 void write(byte[] b, int off, int len)

Writes an array of bytes.

3 void write(int b)

Writes a byte.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterOutputStream
  • java.lang.Object

java.util.zip.CheckedOutputStream.getChecksum() Method Example

Description

The java.util.zip.CheckedOutputStream.getChecksum() method returns the Checksum for this output stream.

Declaration

Following is the declaration for java.util.zip.CheckedOutputStream.getChecksum() method.

public Checksum getChecksum()

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedOutputStream.getChecksum() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CheckedOutputStreamDemo {

   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      byte[] buffer = new byte[1024];

      try {
         FileOutputStream fout = new FileOutputStream(TARGET_FILE);
         CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
         ZipOutputStream zout = new ZipOutputStream(checksum);

         FileInputStream fin = new FileInputStream(SOURCE_FILE);
         zout.putNextEntry(new ZipEntry(SOURCE_FILE));
         int length;
         while((length = fin.read(buffer)) > 0) {
            zout.write(buffer, 0, length);
         }

         zout.closeEntry();
         fin.close();
         zout.close();
         System.out.println("Zip file generated!");
         System.out.println("Adler32 Checksum is : " + checksum.getChecksum().getValue());
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Zip file generated!
Adler32 Checksum is : 2416648244

java.util.zip.CheckedOutputStream.write(byte[] b, int off, int len) Method Example

Description

The java.util.zip.CheckedOutputStream.write(byte[] b, int off, int len) method writes an array of bytes. Will block until the bytes are actually written.

Declaration

Following is the declaration for java.util.zip.CheckedOutputStream.write(byte[] b, int off, int len) method.

public void write(byte[] b, int off, int len)
   throws IOException

Parameters

  • b - the buffer into which the data to be written.

  • off - the start offset in the destination array b.

  • len - the number of bytes to be written.

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedOutputStream.write(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;

public class CheckedOutputStreamDemo {

   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello1.txt";

   public static void main(String[] args) {
      byte[] buffer = new byte[1024];

      try {
         FileOutputStream fout = new FileOutputStream(TARGET_FILE);
         CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());

         FileInputStream fin = new FileInputStream(SOURCE_FILE);

         int length;
         while((length = fin.read(buffer)) > 0) {
            checksum.write(buffer, 0, length);
         }
         fin.close();
         fout.close();
         System.out.println("File copied!");
         System.out.println("Adler32 Checksum is : " + checksum.getChecksum().getValue());
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
}

Let us compile and run the above program, this will produce the following result −

File copied!
Adler32 Checksum is : 1126631102

java.util.zip.CheckedOutputStream.write(int b) Method Example

Description

The java.util.zip.CheckedOutputStream.write(int b) method writes a byte. Will block until the byte is actually written.

Declaration

Following is the declaration for java.util.zip.CheckedOutputStream.write(int b) method.

public void write(int b)
   throws IOException

Parameters

  • b - the byte to be written.

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CheckedOutputStream.write(int b) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;

public class CheckedOutputStreamDemo {

   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello1.txt";

   public static void main(String[] args) {
      byte[] buffer = new byte[1024];

      try {
         FileOutputStream fout = new FileOutputStream(TARGET_FILE);
         CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());

         FileInputStream fin = new FileInputStream(SOURCE_FILE);

         int data = 0;
         while((data = fin.read()) != -1) {
            checksum.write(data);
         }
         fin.close();
         fout.close();
         System.out.println("File copied!");
         System.out.println("Adler32 Checksum is : " + checksum.getChecksum().getValue());
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
}

Let us compile and run the above program, this will produce the following result −

File copied!
Adler32 Checksum is : 1126631102

java.util.zip - CRC32

Introduction

The java.util.zip.CRC32 class is a class that can be used to compute the CRC-32 of a data stream.

Class declaration

Following is the declaration for java.util.zip.CRC32 class −

public class CRC32
   extends Object
      implements Checksum

Constructors

S.N. Constructor & Description
1 CRC32()

Creates a new CRC32 object.

Class methods

S.N. Method & Description
1 long getValue()

Returns the CRC-32 value.

2 void reset()

Resets the CRC-32 to initial value.

3 void update(byte[] b)

Updates the CRC-32 checksum with the specified array of bytes.

4 void update(byte[] b, int off, int len)

Updates the CRC-32 checksum with the specified array of bytes.

5 void update(int b)

Updates the CRC-32 checksum with the specified byte (the low eight bits of the argument b).

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.util.zip.CRC32.getValue() Method Example

Description

The java.util.zip.CRC32.getValue method returns the checksum value.

Declaration

Following is the declaration for java.util.zip.CRC32.getValue method.

public long getValue()

Returns

the current checksum value.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.CRC32.getValue() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CRC32Demo {

   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      byte[] buffer = new byte[1024];

      try {
         FileOutputStream fout = new FileOutputStream(TARGET_FILE);
         CheckedOutputStream checksum = new CheckedOutputStream(fout, new CRC32());
         ZipOutputStream zout = new ZipOutputStream(checksum);

         FileInputStream fin = new FileInputStream(SOURCE_FILE);
         zout.putNextEntry(new ZipEntry(SOURCE_FILE));
         int length;
         while((length = fin.read(buffer)) > 0) {
            zout.write(buffer, 0, length);
         }

         zout.closeEntry();
         fin.close();
         zout.close();
         System.out.println("Zip file generated!");
         System.out.println("CRC32 Checksum is : " + checksum.getChecksum().getValue());
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Zip file generated!
CRC32 Checksum is : 3847524486

java.util.zip.CRC32.reset() Method Example

Description

The java.util.zip.CRC32.reset() method resets the checksum to initial value.

Declaration

Following is the declaration for java.util.zip.CRC32.reset() method.

public void reset()

Returns

the current checksum value.

Example

The following example shows the usage of java.util.zip.CRC32.reset() method.

package com.tutorialspoint;

import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class CRC32Demo {

   public static void main(String[] args) {
      String message = "Welcome to Tutorialspoint.com";
      byte bytes[] = message.getBytes();
      Checksum checksum = new CRC32();
      checksum.reset();       
      checksum.update(bytes,0,bytes.length);
      long checksumValue = checksum.getValue();
      System.out.println("CRC32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

CRC32 checksum :1734172551

java.util.zip.CRC32.update(byte[] b) Method Example

Description

The java.util.zip.CRC32.update(byte[] b) method updates the checksum with the specified array of bytes.

Declaration

Following is the declaration for java.util.zip.CRC32.update(byte[] b) method.

public void update(byte[] b)

Parameters

  • b - the byte array to update the checksum with.

Example

The following example shows the usage of java.util.zip.CRC32.update(byte[] b) method.

package com.tutorialspoint;

import java.util.zip.CRC32;

public class CRC32Demo {

   public static void main(String[] args) {
      String message = "Welcome to Tutorialspoint.com";
      byte bytes[] = message.getBytes();

      CRC32 checksum = new CRC32();
      checksum.reset();       

      checksum.update(bytes);
      long checksumValue = checksum.getValue();

      System.out.println("CRC32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

CRC32 checksum :1734172551

java.util.zip.CRC32.update(byte[] b, int off, int len) Method Example

Description

The java.util.zip.CRC32.update(byte[] b, int off, int len) method updates the checksum with the specified array of bytes.

Declaration

Following is the declaration for java.util.zip.CRC32.update(byte[] b, int off, int len) method.

public void update(byte[] b, int off, int len)

Parameters

  • b - the byte array to update the checksum with.

  • off - the start offset of the data.

  • len - the number of bytes to use for the update.

Example

The following example shows the usage of java.util.zip.CRC32.update(byte[] b) method.

package com.tutorialspoint;

import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class CRC32Demo {

   public static void main(String[] args) {
      String message = "Welcome to Tutorialspoint.com";
      byte bytes[] = message.getBytes();
      Checksum checksum = new CRC32();
      checksum.reset();       
      checksum.update(bytes,0,bytes.length);
      long checksumValue = checksum.getValue();
      System.out.println("CRC32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

CRC32 checksum :1734172551

java.util.zip.CRC32.update(int b) Method Example

Description

The java.util.zip.CRC32.update(int b) method updates the checksum with the specified byte (the low eight bits of the argument b).

Declaration

Following is the declaration for java.util.zip.CRC32.update(int b) method.

public void update(int b)

Parameters

  • b - the byte to update the checksum with.

Example

The following example shows the usage of java.util.zip.CRC32.update(byte[] b) method.

package com.tutorialspoint;

import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class CRC32Demo {
   public static void main(String[] args) {
      int bytes = 55;

      Checksum checksum = new CRC32();
      checksum.reset();       

      checksum.update(bytes);
      long checksumValue = checksum.getValue();

      System.out.println("CRC32 checksum :" + checksumValue);
   }
}

Let us compile and run the above program, this will produce the following result −

CRC32 checksum :1790921346

java.util.zip - Deflater

Introduction

The java.util.zip.Deflater class provides support for general purpose compression using the popular ZLIB compression library. The ZLIB compression library was initially developed as part of the PNG graphics standard and is not protected by patents. It is fully described in the specifications at the java.util.zip package description.

Class declaration

Following is the declaration for java.util.zip.Deflater class −

public class Deflater
   extends Object

Fields

Following are the fields for java.util.zip.Deflater class −

  • static int BEST_COMPRESSION - Compression level for best compression.

  • static int BEST_SPEED - Compression level for fastest compression.

  • static int DEFAULT_COMPRESSION - Default compression level.

  • static int DEFAULT_STRATEGY - Default compression strategy.

  • static int DEFLATED - Compression method for the deflate algorithm (the only one currently supported).

  • static int FILTERED - Compression strategy best used for data consisting mostly of small values with a somewhat random distribution.

  • static int FULL_FLUSH - Compression flush mode used to flush out all pending output and reset the deflater.

  • static int HUFFMAN_ONLY - Compression strategy for Huffman coding only.

  • static int NO_COMPRESSION - Compression level for no compression.

  • static int NO_FLUSH - Compression flush mode used to achieve best compression result.

  • static int SYNC_FLUSH - Compression flush mode used to flush out all pending output; may degrade compression for some compression algorithms.

Constructors

S.N. Constructor & Description
1 Deflater()

Creates a new compressor with the default compression level.

2 Deflater(int level)

Creates a new compressor using the specified compression level.

3 Deflater(int level, boolean nowrap)

Creates a new compressor using the specified compression level.

Class methods

S.N. Method & Description
1 int deflate(byte[] b)

Compresses the input data and fills specified buffer with compressed data.

2 int deflate(byte[] b, int off, int len)

Compresses the input data and fills specified buffer with compressed data.

3 int deflate(byte[] b, int off, int len, int flush)

Compresses the input data and fills the specified buffer with compressed data.

4 void end()

Closes the compressor and discards any unprocessed input.

5 void finish()

When called, indicates that compression should end with the current contents of the input buffer.

6 boolean finished()

Returns true if the end of the compressed data output stream has been reached.

7 int getAdler()

Returns the ADLER-32 value of the uncompressed data.

8 long getBytesRead()

Returns the total number of uncompressed bytes input so far.

9 long getBytesWritten()

Returns the total number of compressed bytes output so far.

10 int getTotalIn()

Returns the total number of uncompressed bytes input so far.

11 int getTotalOut()

Returns the total number of compressed bytes output so far.

12 boolean needsInput()

Returns true if the input data buffer is empty and setInput() should be called in order to provide more input.

13 void reset()

Resets deflater so that a new set of input data can be processed.

14 void setDictionary(byte[] b)

Sets preset dictionary for compression.

15 void setDictionary(byte[] b, int off, int len)

Sets preset dictionary for compression.

16 void setInput(byte[] b)

Sets input data for compression.

17 void setInput(byte[] b, int off, int len)

Sets input data for compression.

18 void setLevel(int level)

Sets the current compression level to the specified value.

19 void setStrategy(int strategy)

Sets the compression strategy to the specified value.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.util.zip.Deflater.deflate(byte[] b) Method Example

Description

The java.util.zip.Deflater.deflate(byte[] b) method compresses the input data and fills specified buffer with compressed data. Returns actual number of bytes of compressed data. A return value of 0 indicates that needsInput should be called in order to determine if more input data is required.

Declaration

Following is the declaration for java.util.zip.Deflater.deflate(byte[] b) method.

public int deflate(byte[] b)

Parameters

  • b - the buffer for the compressed data.

Returns

The actual number of bytes of compressed data written to the output buffer.

Example

The following example shows the usage of java.util.zip.Deflater.deflate(byte[] b) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Deflater.deflate(byte[] b, int off, int len)Method Example

Description

The java.util.zip.Deflater.deflate(byte[] b, int off, int len) method compresses the input data and fills specified buffer with compressed data. Returns actual number of bytes of compressed data. A return value of 0 indicates that needsInput should be called in order to determine if more input data is required.

Declaration

Following is the declaration for java.util.zip.Deflater.deflate(byte[] b, int off, int len) method.

public int deflate(byte[] b, int off, int len)

Parameters

  • b - the buffer for the compressed data.

  • off - the start offset of the data.

  • len - the maximum number of bytes of compressed data.

Returns

The actual number of bytes of compressed data written to the output buffer.

Example

The following example shows the usage of java.util.zip.Deflater.deflate(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0,output.length);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Deflater.deflate(byte[] b, int off, int len, int flush)Method Example

Description

The java.util.zip.Deflater.deflate(byte[] b, int off, int len, int flush) method compresses the input data and fills the specified buffer with compressed data. Returns actual number of bytes of data compressed.

Declaration

Following is the declaration for java.util.zip.Deflater.deflate(byte[] b, int off, int len, int flush) method.

public int deflate(byte[] b, int off, int len, int flush)

Parameters

  • b - the buffer for the compressed data.

  • off - the start offset of the data.

  • len - the maximum number of bytes of compressed data.

  • flush - the compression flush mode.

Returns

The actual number of bytes of compressed data written to the output buffer.

Exceptions

  • IllegalArgumentException - if the flush mode is invalid.

The actual number of bytes of compressed data written to the output buffer.

Example

The following example shows the usage of java.util.zip.Deflater.deflate(byte[] b, int off, int len, int flush) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0,output.length, Deflater.NO_FLUSH);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Deflater.end() Method Example

Description

The java.util.zip.Deflater.end() method closes the compressor and discards any unprocessed input. This method should be called when the compressor is no longer being used, but will also be called automatically by the finalize() method. Once this method is called, the behavior of the Deflater object is undefined.

Declaration

Following is the declaration for java.util.zip.Deflater.end() method.

public void end()

Example

The following example shows the usage of java.util.zip.Deflater.end() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Deflater.finish() Method Example

Description

The java.util.zip.Deflater.finish() method when called, indicates that compression should end with the current contents of the input buffer.

Declaration

Following is the declaration for java.util.zip.Deflater.finish() method.

public void finish()

Example

The following example shows the usage of java.util.zip.Deflater.finish() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Deflater.finished() Method Example

Description

The java.util.zip.Deflater.finished() method returns true if the end of the compressed data output stream has been reached.

Declaration

Following is the declaration for java.util.zip.Deflater.finished() method.

public boolean finished()

Returns

true if the end of the compressed data output stream has been reached.

Example

The following example shows the usage of java.util.zip.Deflater.finished() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Deflater.getAdler() Method Example

Description

The java.util.zip.Deflater.getAdler() method returns the ADLER-32 value of the uncompressed data.

Declaration

Following is the declaration for java.util.zip.Deflater.getAdler() method.

public int getAdler()

Returns

the ADLER-32 value of the uncompressed data.

Example

The following example shows the usage of java.util.zip.Deflater.getAdler() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.getBytesRead() Method Example

Description

The java.util.zip.Deflater.getBytesRead() method returns the total number of uncompressed bytes input so far.

Declaration

Following is the declaration for java.util.zip.Deflater.getBytesRead() method.

public long getBytesRead()

Returns

the total (non-negative) number of uncompressed bytes input so far.

Example

The following example shows the usage of java.util.zip.Deflater.getBytesRead() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Bytes Read :" + deflater.getBytesRead());     
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Bytes Read :300
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.getBytesWritten() Method Example

Description

The java.util.zip.Deflater.getBytesWritten() method returns the total number of compressed bytes output so far.

Declaration

Following is the declaration for java.util.zip.Deflater.getBytesWritten() method.

public long getBytesWritten()

Returns

the total (non-negative) number of uncompressed bytes input so far.

Example

The following example shows the usage of java.util.zip.Deflater.getBytesWritten() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Bytes Written :" + deflater.getBytesWritten());   
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Bytes Written :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.getTotalIn() Method Example

Description

The java.util.zip.Deflater.getTotalIn() method returns the total number of uncompressed bytes input so far.

Declaration

Following is the declaration for java.util.zip.Deflater.getTotalIn() method.

public int getTotalIn()

Returns

the total number of uncompressed bytes input so far.

Example

The following example shows the usage of java.util.zip.Deflater.getTotalIn() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.getTotalOut() Method Example

Description

The java.util.zip.Deflater.getTotalOut() method returns the total number of compressed bytes output so far.

Declaration

Following is the declaration for java.util.zip.Deflater.getTotalOut() method.

public int getTotalOut()

Returns

the total number of compressed bytes output so far.

Example

The following example shows the usage of java.util.zip.Deflater.getTotalOut() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.needsInput() Method Example

Description

The java.util.zip.Deflater.needsInput() method returns true if the input data buffer is empty and setInput() should be called in order to provide more input.

Declaration

Following is the declaration for java.util.zip.Deflater.needsInput() method.

public boolean needsInput()

Returns

true if the input data buffer is empty and setInput() should be called in order to provide more input.

Example

The following example shows the usage of java.util.zip.Deflater.needsInput() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      // Compress the bytes
      byte[] output = new byte[1024];

      Deflater deflater = new Deflater();
      int inCount = input.length;  
      int inPosition = 0;
      int outPosition = 0;

      int MAX_BUFFER_SIZE = 10;
      while(!deflater.finished()){
         int want = -1;
         int got;
         if (deflater.needsInput() && inCount != 0) {
            want = (inCount < MAX_BUFFER_SIZE) ? inCount : MAX_BUFFER_SIZE;

            deflater.setInput(input, inPosition, want);

            inCount -= want;
            inPosition += want;
            if (inCount == 0) {
               deflater.finish();
            }
         }
         // deflate to current position in output buffer
         int compCount;

         compCount = deflater.deflate(output, outPosition, MAX_BUFFER_SIZE);
         outPosition += compCount;
      }

      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());     
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + outPosition);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, outPosition);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.reset() Method Example

Description

The java.util.zip.Deflater.reset() method resets deflater so that a new set of input data can be processed. Keeps current compression level and strategy settings.

Declaration

Following is the declaration for java.util.zip.Deflater.reset() method.

public void reset()

Example

The following example shows the usage of java.util.zip.Deflater.reset() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.reset();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.setDictionary(byte[] b) Method Example

Description

The java.util.zip.Deflater.setDictionary(byte[] b) method sets preset dictionary for compression. A preset dictionary is used when the history buffer can be predetermined. When the data is later uncompressed with Inflater.inflate(), Inflater.getAdler() can be called in order to get the Adler-32 value of the dictionary required for decompression.

Declaration

Following is the declaration for java.util.zip.Deflater.setDictionary(byte[] b) method.

public void setDictionary(byte[] b)

Parameters

  • b - the dictionary data bytes.

Example

The following example shows the usage of java.util.zip.Deflater.setDictionary(byte[] b) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
 
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.setDictionary(dictionary.getBytes("UTF-8"));
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      if(inflater.needsDictionary()){
    
         inflater.setDictionary(dictionary.getBytes("UTF-8"));
 
         resultLength = inflater.inflate(result);
      }
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.setDictionary(byte[] b, int off, int len) Method Example

Description

The java.util.zip.Deflater.setDictionary(byte[] b, int off, int len) method sets preset dictionary for compression. A preset dictionary is used when the history buffer can be predetermined. When the data is later uncompressed with Inflater.inflate(), Inflater.getAdler() can be called in order to get the Adler-32 value of the dictionary required for decompression.

Declaration

Following is the declaration for java.util.zip.Deflater.setDictionary(byte[] b, int off, int len) method.

public void setDictionary(byte[] b, int off, int len)

Parameters

  • b - the dictionary data bytes.

  • off - the start offset of the data.

  • len - the length of the data.

Example

The following example shows the usage of java.util.zip.Deflater.setDictionary(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
 
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.setDictionary(dictionary.getBytes("UTF-8"),0, dictionary.length());
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      if(inflater.needsDictionary()){
    
         inflater.setDictionary(dictionary.getBytes("UTF-8"),0, dictionary.length());
 
         resultLength = inflater.inflate(result);
      }
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.setInput(byte[] b) Method Example

Description

The java.util.zip.Deflater.setInput(byte[] b) method sets input data for compression. This should be called whenever needsInput() returns true indicating that more input data is required.

Declaration

Following is the declaration for java.util.zip.Deflater.setInput(byte[] b) method.

public void setInput(byte[] b)

Parameters

  • b - the input data bytes.

Example

The following example shows the usage of java.util.zip.Deflater.setInput(byte[] b) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.setInput(byte[] b, int off, int len) Method Example

Description

The java.util.zip.Deflater.setInput(byte[] b, int off, int len) method sets input data for compression. This should be called whenever needsInput() returns true indicating that more input data is required.

Declaration

Following is the declaration for java.util.zip.Deflater.setInput(byte[] b, int off, int len) method.

public void setInput(byte[] b, int off, int len)

Parameters

  • b - the input data bytes.

  • off - he start offset of the data.

  • len - the length of the data.

Example

The following example shows the usage of java.util.zip.Deflater.setInput(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      // Compress the bytes
      byte[] output = new byte[1024];

      Deflater deflater = new Deflater();
      int inCount = input.length;  
      int inPosition = 0;
      int outPosition = 0;

      int MAX_BUFFER_SIZE = 10;
      while(!deflater.finished()){
         int want = -1;
         int got;
         if (deflater.needsInput() && inCount != 0) {
            want = (inCount < MAX_BUFFER_SIZE) ? inCount : MAX_BUFFER_SIZE;

            deflater.setInput(input, inPosition, want);

            inCount -= want;
            inPosition += want;
            if (inCount == 0) {
               deflater.finish();
            }
         }
         // deflate to current position in output buffer
         int compCount;

         compCount = deflater.deflate(output, outPosition, MAX_BUFFER_SIZE);
         outPosition += compCount;
      }

      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());     
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + outPosition);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, outPosition);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.setLevel(int level) Method Example

Description

The java.util.zip.Deflater.setLevel(int level) method sets the current compression level to the specified value.

Declaration

Following is the declaration for java.util.zip.Deflater.setLevel(int level) method.

public void setLevel(int level)

Parameters

  • level - the new compression level (0-9).

Exceptions

  • IllegalArgumentException - if the compression level is invalid.

Example

The following example shows the usage of java.util.zip.Deflater.setLevel(int level) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.setLevel(Deflater.DEFAULT_COMPRESSION);
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Deflater.setStrategy(int strategy) Method Example

Description

The java.util.zip.Deflater.setStrategy(int strategy) method sets the compression strategy to the specified value.

Declaration

Following is the declaration for java.util.zip.Deflater.setStrategy(int strategy) method.

public void setStrategy(int strategy)

Parameters

  • strategy - the new compression strategy.

Exceptions

  • IllegalArgumentException - if the compression strategy is invalid.

Example

The following example shows the usage of java.util.zip.Deflater.setStrategy(int strategy) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class DeflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.setStrategy(Deflater.DEFAULT_STRATEGY);
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip - DeflaterInputStream

Introduction

The java.util.zip.DeflaterInputStream class implements an input stream filter for compressing data in the "deflate" compression format.

Class declaration

Following is the declaration for java.util.zip.DeflaterInputStream class −

public class DeflaterInputStream
   extends FilterInputStream

Fields

Following are the fields for java.util.zip.DeflaterInputStream class −

  • protected byte[] buf - Input buffer for reading compressed data.

  • protected Deflater def - Compressor for this stream.

Constructors

S.N. Constructor & Description
1 DeflaterInputStream(InputStream in)

Creates a new input stream with a default compressor and buffer size.

2 DeflaterInputStream(InputStream in, Deflater defl)

Creates a new input stream with the specified compressor and a default buffer size.

3 DeflaterInputStream(InputStream in, Deflater defl, int bufLen)

Creates a new input stream with the specified compressor and buffer size.

Class methods

S.N. Method & Description
1 int available()

Returns 0 after EOF has been reached, otherwise always return 1.

2 void close()

Closes this input stream and its underlying input stream, discarding any pending uncompressed data.

3 int read()

Reads a single byte of compressed data from the input stream.

4 int read(byte[] b, int off, int len)

Reads compressed data into a byte array.

5 long skip(long n)

Skips over and discards data from the input stream.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterInputStream
  • java.lang.Object

java.util.zip.DeflaterInputStream.available() Method Example

Description

The java.util.zip.DeflaterInputStream.available() method returns 0 after EOF has been reached, otherwise always return 1.

Declaration

Following is the declaration for java.util.zip.DeflaterInputStream.available() method.

public int available()
   throws IOException

Returns

zero after the end of the underlying input stream has been reached, otherwise always returns 1.

Exceptions

  • IOException - if an I/O error occurs or if this stream is already closed.

Example

The following example shows the usage of java.util.zip.DeflaterInputStream.available() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class DeflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.DeflaterInputStream.close() Method Example

Description

The java.util.zip.DeflaterInputStream.close() method closes this input stream and its underlying input stream, discarding any pending uncompressed data.

Declaration

Following is the declaration for java.util.zip.DeflaterInputStream.close() method.

public int close()
   throws IOException

Exceptions

  • IOException - if an I/O error occurs.

Example

The following example shows the usage of java.util.zip.DeflaterInputStream.close() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class DeflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.DeflaterInputStream.read() Method Example

Description

The java.util.zip.DeflaterInputStream.read() method reads a single byte of compressed data from the input stream. This method will block until some input can be read and compressed.

Declaration

Following is the declaration for java.util.zip.DeflaterInputStream.read() method.

public int read()
   throws IOException

Returns

a single byte of compressed data, or -1 if the end of the uncompressed input stream is reached.

Exceptions

  • IOException - if an I/O error occurs or if this stream is already closed.

Example

The following example shows the usage of java.util.zip.DeflaterInputStream.read() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class DeflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) Method Example

Description

The java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) method reads a single byte of compressed data from the input stream. This method will block until some input can be read and compressed.

Declaration

Following is the declaration for java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) method.

public int read(byte[] b, int off, int len)
   throws IOException

Parameters

  • b - buffer into which the data is read.

  • off - starting offset of the data within b.

  • len - maximum number of compressed bytes to read into b.

Returns

the actual number of bytes read, or -1 if the end of the uncompressed input stream is reached.

Exceptions

  • IndexOutOfBoundsException - if len > b.length - off.

  • IOException - if an I/O error occurs or if this stream is already closed.

Example

The following example shows the usage of java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class DeflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      inflaterInputStream.read(result,0,result.length);
      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(result,0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.DeflaterInputStream.skip(long n) Method Example

Description

The java.util.zip.DeflaterInputStream.skip(long n) method skips over and discards data from the input stream. This method may block until the specified number of bytes are read and skipped. Note: While n is given as a long, the maximum number of bytes which can be skipped is Integer.MAX_VALUE.

Declaration

Following is the declaration for java.util.zip.DeflaterInputStream.skip(long n) method.

public long skip(long n)
   throws IOException

Parameters

  • n - number of bytes to be skipped.

Returns

the actual number of bytes skipped.

Exceptions

  • IOException - if an I/O error occurs or if this stream is already closed.

Example

The following example shows the usage of java.util.zip.DeflaterInputStream.skip(long n) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class DeflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];
      System.out.println("Before Skipping, available: " + inflaterInputStream.available());
      inflaterInputStream.skip(result.length);
      System.out.println("After Skipping, available: " + inflaterInputStream.available());
      inflaterInputStream.close();     
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
Before Skipping, available: 1
After Skipping, available: 0

java.util.zip - DeflaterOutputStream

Introduction

The java.util.zip.DeflaterOutputStream class implements an output stream filter for compressing data in the "deflate" compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream.

Class declaration

Following is the declaration for java.util.zip.DeflaterOutputStream class −

public class DeflaterOutputStream
   extends FilterOutputStream

Fields

Following are the fields for java.util.zip.DeflaterOutputStream class −

  • protected byte[] buf - Output buffer for writing compressed data.

  • protected Deflater def - Compressor for this stream.

Constructors

S.N. Constructor & Description
1 DeflaterOutputStream(OutputStream out)

Creates a new output stream with a default compressor and buffer size.

2 DeflaterOutputStream(OutputStream out, boolean syncFlush)

Creates a new output stream with a default compressor, a default buffer size and the specified flush mode.

3 DeflaterOutputStream(OutputStream out, Deflater def)

Creates a new output stream with the specified compressor and a default buffer size.

4 DeflaterOutputStream(OutputStream out, Deflater def, boolean syncFlush)

Creates a new output stream with the specified compressor, flush mode and a default buffer size.

5 DeflaterOutputStream(OutputStream out, Deflater def, int size)

Creates a new output stream with the specified compressor and buffer size.

6 DeflaterOutputStream(OutputStream out, Deflater def, int size, boolean syncFlush)

Creates a new output stream with the specified compressor, buffer size and flush mode.

Class methods

S.N. Method & Description
1 void close()

Writes remaining compressed data to the output stream and closes the underlying stream.

2 void finish()

Finishes writing compressed data to the output stream without closing the underlying stream.

3 void flush()

Flushes the compressed output stream.

4 void write(byte[] b, int off, int len)

Writes an array of bytes to the compressed output stream.

5 void write(int b)

Writes a byte to the compressed output stream.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterOutputStream
  • java.lang.Object

java.util.zip.DeflaterOutputStream.close() Method Example

Description

The java.util.zip.DeflaterOutputStream.close() method writes remaining compressed data to the output stream and closes the underlying stream.

Declaration

Following is the declaration for java.util.zip.DeflaterOutputStream.close() method.

public void close()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.DeflaterOutputStream.close() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class DeflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      InflaterInputStream inputStream = new InflaterInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer);

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.DeflaterOutputStream.finish() Method Example

Description

The java.util.zip.DeflaterOutputStream.finish() method finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Declaration

Following is the declaration for java.util.zip.DeflaterOutputStream.finish() method.

public void finish()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.DeflaterOutputStream.finish() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class DeflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
 outputStream.finish();
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      InflaterInputStream inputStream = new InflaterInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer);

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.DeflaterOutputStream.flush() Method Example

Description

The java.util.zip.DeflaterOutputStream.flush() method flushes the compressed output stream. If syncFlush is true when this compressed output stream is constructed, this method first flushes the underlying compressor with the flush mode Deflater.SYNC_FLUSH to force all pending data to be flushed out to the output stream and then flushes the output stream. Otherwise this method only flushes the output stream without flushing the compressor.

Declaration

Following is the declaration for java.util.zip.DeflaterOutputStream.flush() method.

public void flush()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.DeflaterOutputStream.flush() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class DeflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.flush();
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      InflaterInputStream inputStream = new InflaterInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer);

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.DeflaterOutputStream.write(byte[] b, int off, int len) Method Example

Description

The java.util.zip.DeflaterOutputStream.write(byte[] b, int off, int len) method writes an array of bytes to the compressed output stream. This method will block until all the bytes are written.

Declaration

Following is the declaration for java.util.zip.DeflaterOutputStream.write(byte[] b, int off, int len) method.

public void write(byte[] b, int off, int len)
 throws IOException

Parameters

  • b - the data to be written.

  • off - the start offset of the data.

  • len - the length of the data.

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.DeflaterOutputStream.write(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class DeflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input, 0, input.length);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      InflaterInputStream inputStream = new InflaterInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer);

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.DeflaterOutputStream.write(int b) Method Example

Description

The java.util.zip.DeflaterOutputStream.write(int b) method writes a byte to the compressed output stream. This method will block until the byte can be written.

Declaration

Following is the declaration for java.util.zip.DeflaterOutputStream.write(int b) method.

public void write(int b)
 throws IOException

Parameters

  • b - the byte to be written.

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.DeflaterOutputStream.write(int b) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class DeflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      for(byte b: input){
         outputStream.write(b);
      }
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      InflaterInputStream inputStream = new InflaterInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer);

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip - GZIPInputStream

Introduction

The java.util.zip.GZIPInputStream class implements a stream filter for reading compressed data in the GZIP file format.

Class declaration

Following is the declaration for java.util.zip.GZIPInputStream class −

public class GZIPInputStream
   extends InflaterInputStream

Fields

Following are the fields for java.util.zip.GZIPInputStream class −

  • protected CRC32 crc - CRC-32 for uncompressed data.

  • protected boolean eos - Indicates end of input stream.

  • static int GZIP_MAGIC - GZIP header magic number.

Constructors

S.N. Constructor & Description
1 GZIPInputStream(InputStream in)

Creates a new input stream with a default buffer size.

2 GZIPInputStream(InputStream in, int size)

Creates a new input stream with the specified buffer size.

Class methods

S.N. Method & Description
1 void close()

Closes this input stream and releases any system resources associated with the stream.

2 int read(byte[] buf, int off, int len)

Reads uncompressed data into an array of bytes.

Methods inherited

This class inherits methods from the following classes −

  • java.util.zip.InflaterInputStream
  • java.io.FilterInputStream
  • java.lang.Object

java.util.zip.GZIPInputStream.close() Method Example

Description

The java.util.zip.GZIPInputStream.close() method closes this input stream and releases any system resources associated with the stream.

Declaration

Following is the declaration for java.util.zip.GZIPInputStream.close() method.

public void close()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.GZIPInputStream.close() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPInputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
    
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      GZIPOutputStream outputStream = new GZIPOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      GZIPInputStream inputStream = new GZIPInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer,0,readBuffer.length);
      inputStream.close();
      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.GZIPInputStream.read(byte[] buf, int off, int len) Method Example

Description

The java.util.zip.GZIPInputStream.read(byte[] buf, int off, int len) method reads uncompressed data into an array of bytes. If len is not zero, the method will block until some input can be decompressed; otherwise, no bytes are read and 0 is returned.

Declaration

Following is the declaration for java.util.zip.GZIPInputStream.read(byte[] buf, int off, int len) method.

public int read(byte[] buf, int off, int len)
   throws IOException

Parameters

  • buf - 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 stream is reached.

Exceptions

  • NullPointerException - If buf is null.

  • IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than buf.length - off.

  • ZipException - if the compressed input data is corrupt.

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.GZIPInputStream.read(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPInputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
    
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      GZIPOutputStream outputStream = new GZIPOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      GZIPInputStream inputStream = new GZIPInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer,0,readBuffer.length);
      inputStream.close();
      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip - GZIPOutputStream

Introduction

The java.util.zip.GZIPOutputStream class implements a stream filter for writing compressed data in the GZIP file format.

Class declaration

Following is the declaration for java.util.zip.GZIPOutputStream class −

public class GZIPOutputStream
   extends DeflaterOutputStream

Fields

Following are the fields for java.util.zip.GZIPOutputStream class −

  • protected CRC32 crc - CRC-32 for uncompressed data.

Constructors

S.N. Constructor & Description
1 GZIPOutputStream(OutputStream out)

Creates a new output stream with a default buffer size.

2 GZIPOutputStream(OutputStream out, boolean syncFlush)

Creates a new output stream with a default buffer size and the specified flush mode.

3 GZIPOutputStream(OutputStream out, int size)

Creates a new output stream with the specified buffer size.

4 GZIPOutputStream(OutputStream out, int size, boolean syncFlush)

Creates a new output stream with the specified buffer size and flush mode.

Class methods

S.N. Method & Description
1 void finish()

Finishes writing compressed data to the output stream without closing the underlying stream.

2 int write(byte[] buf, int off, int len)

Writes array of bytes to the compressed output stream.

Methods inherited

This class inherits methods from the following classes −

  • java.util.zip.DeflaterOutputStream
  • java.io.FilterOutputStream
  • java.lang.Object

java.util.zip.GZIPOutputStream.finish() Method Example

Description

The java.util.zip.GZIPOutputStream.finish() method finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Declaration

Following is the declaration for java.util.zip.GZIPOutputStream.finish() method.

public void finish()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.GZIPOutputStream.finish() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
    
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      GZIPOutputStream outputStream = new GZIPOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.finish();
 outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      GZIPInputStream inputStream = new GZIPInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer,0,readBuffer.length);
      inputStream.close();
      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len) Method Example

Description

The java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len) method writes array of bytes to the compressed output stream. This method will block until all the bytes are written.

Declaration

Following is the declaration for java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len) method.

public int write(byte[] buf, int off, int len)
   throws IOException

Parameters

  • buf - the data to be written.

  • off - the start offset of the data.

  • len - the length of the data.

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
    
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      GZIPOutputStream outputStream = new GZIPOutputStream(arrayOutputStream);
      outputStream.write(input,0, input.length);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      GZIPInputStream inputStream = new GZIPInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer,0,readBuffer.length);
      inputStream.close();
      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip - Inflater

Introduction

The java.util.zip.Inflater class provides support for general purpose decompression using the popular ZLIB compression library. The ZLIB compression library was initially developed as part of the PNG graphics standard and is not protected by patents. It is fully described in the specifications at the java.util.zip package description.

Class declaration

Following is the declaration for java.util.zip.Inflater class −

public class Inflater
   extends Object

Constructors

S.N. Constructor & Description
1 Inflater()

Creates a new decompressor.

2 Inflater(boolean nowrap)

Creates a new decompressor.

Class methods

S.N. Method & Description
1 void end()

Closes the decompressor and discards any unprocessed input.

2 boolean finished()

Returns true if the end of the compressed data stream has been reached.

3 int getAdler()

Returns the ADLER-32 value of the uncompressed data.

4 long getBytesRead()

Returns the total number of compressed bytes input so far.

5 long getBytesWritten()

Returns the total number of uncompressed bytes output so far.

6 int getRemaining()

Returns the total number of bytes remaining in the input buffer.

7 int getTotalIn()

Returns the total number of compressed bytes input so far.

8 int getTotalOut()

Returns the total number of uncompressed bytes output so far.

9 int inflate(byte[] b)

Uncompresses bytes into specified buffer.

10 int inflate(byte[] b, int off, int len)

Uncompresses bytes into specified buffer.

11 boolean needsDictionary()

Returns true if a preset dictionary is needed for decompression.

12 boolean needsInput()

Returns true if no data remains in the input buffer.

13 void reset()

Resets inflater so that a new set of input data can be processed.

14 void setDictionary(byte[] b)

Sets the preset dictionary to the given array of bytes.

15 void setDictionary(byte[] b, int off, int len)

Sets the preset dictionary to the given array of bytes.

16 void setInput(byte[] b)

Sets input data for decompression.

17 void setInput(byte[] b, int off, int len)

Sets input data for decompression.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

java.util.zip.Inflater.end() Method Example

Description

The java.util.zip.Inflater.end() method closes the decompressor and discards any unprocessed input. This method should be called when the decompressor is no longer being used, but will also be called automatically by the finalize() method. Once this method is called, the behavior of the Inflater object is undefined.

Declaration

Following is the declaration for java.util.zip.Inflater.end() method.

public void end()

Example

The following example shows the usage of java.util.zip.Inflater.end() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Inflater.finished() Method Example

Description

The java.util.zip.Inflater.finished() method returns true if the end of the compressed data stream has been reached.

Declaration

Following is the declaration for java.util.zip.Inflater.finished() method.

public boolean finished()

Returns

true if the end of the compressed data stream has been reached.

Example

The following example shows the usage of java.util.zip.Inflater.finished() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Inflater.getAdler() Method Example

Description

The java.util.zip.Inflater.getAdler() method returns the ADLER-32 value of the uncompressed data.

Declaration

Following is the declaration for java.util.zip.Inflater.getAdler() method.

public int getAdler()

Returns

the ADLER-32 value of the uncompressed data.

Example

The following example shows the usage of java.util.zip.Inflater.getAdler() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.getBytesRead() Method Example

Description

The java.util.zip.Inflater.getBytesRead() method returns the total number of compressed bytes input so far.

Declaration

Following is the declaration for java.util.zip.Inflater.getBytesRead() method.

public long getBytesRead()

Returns

the total (non-negative) number of compressed bytes input so far.

Example

The following example shows the usage of java.util.zip.Inflater.getBytesRead() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Bytes Read :" + deflater.getBytesRead());     
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
 System.out.println("Bytes Read :" + inflater.getBytesRead()); 
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Bytes Read :300
Compressed Message Checksum :368538129
Compressed Message length : 42
Bytes Read :42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.getBytesWritten() Method Example

Description

The java.util.zip.Inflater.getBytesWritten() method returns the total number of uncompressed bytes output so far.

Declaration

Following is the declaration for java.util.zip.Inflater.getBytesWritten() method.

public long getBytesWritten()

Returns

the total (non-negative) number of uncompressed bytes input so far.

Example

The following example shows the usage of java.util.zip.Inflater.getBytesWritten() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Bytes Written :" + deflater.getBytesWritten());   
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
 System.out.println("Bytes Written :" + inflater.getBytesWritten());   
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Bytes Written :42
Compressed Message Checksum :368538129
Compressed Message length : 42
Bytes Written :300
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.getTotalIn() Method Example

Description

The java.util.zip.Inflater.getTotalIn() method returns the total number of compressed bytes input so far.

Declaration

Following is the declaration for java.util.zip.Inflater.getTotalIn() method.

public int getTotalIn()

Returns

the total number of compressed bytes input so far.

Example

The following example shows the usage of java.util.zip.Inflater.getTotalIn() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
 System.out.println("Total compressed bytes input :" + inflater.getTotalIn());
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
Total compressed bytes input :42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.getRemaining() Method Example

Description

The java.util.zip.Inflater.getRemaining() method returns the total number of bytes remaining in the input buffer. This can be used to find out what bytes still remain in the input buffer after decompression has finished.

Declaration

Following is the declaration for java.util.zip.Inflater.getRemaining() method.

public int getRemaining()

Returns

the total number of bytes remaining in the input buffer.

Example

The following example shows the usage of java.util.zip.Inflater.getRemaining() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
 System.out.println("Remaining compressed bytes input :" + inflater.getRemaining());
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
Remaining compressed bytes input :0
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.getTotalOut() Method Example

Description

The java.util.zip.Inflater.getTotalOut() method returns the total number of uncompressed bytes output so far.

Declaration

Following is the declaration for java.util.zip.Inflater.getTotalOut() method.

public int getTotalOut()

Returns

the total number of uncompressed bytes output so far.

Example

The following example shows the usage of java.util.zip.Inflater.getTotalOut() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
 System.out.println("Total uncompressed bytes output :" + inflater.getTotalOut());
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
Total uncompressed bytes output :300
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.inflate(byte[] b) Method Example

Description

The java.util.zip.Inflater.inflate(byte[] b) method uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the latter case, getAdler() can be used to get the Adler-32 value of the dictionary required.

Declaration

Following is the declaration for java.util.zip.Inflater.inflate(byte[] b) method.

public int inflate(byte[] b)
   throws DataFormatException

Parameters

  • b - the buffer for the uncompressed data.

Returns

the actual number of uncompressed bytes.

Exceptions

  • DataFormatException - if the compressed data format is invalid.

Example

The following example shows the usage of java.util.zip.Inflater.inflate(byte[] b) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Inflater.inflate(byte[] b, int off, int len) Method Example

Description

The java.util.zip.Inflater.inflate(byte[] b, int off, int len) method uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the latter case, getAdler() can be used to get the Adler-32 value of the dictionary required.

Declaration

Following is the declaration for java.util.zip.Inflater.inflate(byte[] b, int off, int len) method.

public int inflate(byte[] b, int off, int len)
   throws DataFormatException

Parameters

  • b - the buffer for the uncompressed data.

  • off - the start offset of the data.

  • len - the maximum number of bytes of uncompressed data.

Returns

The actual number of bytes of uncompressed bytes.

Exceptions

  • DataFormatException - if the compressed data format is invalid.

Example

The following example shows the usage of java.util.zip.Inflater.inflate(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0,output.length);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result, 0 , result.length);
      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Inflater.needsDictionary() Method Example

Description

The java.util.zip.Inflater.needsDictionary() method returns true if a preset dictionary is needed for decompression.

Declaration

Following is the declaration for java.util.zip.Inflater.needsDictionary() method.

public boolean needsDictionary()

Returns

true if a preset dictionary is needed for decompression.

Example

The following example shows the usage of java.util.zip.Inflater.needsDictionary() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
 
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.setDictionary(dictionary.getBytes("UTF-8"));
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      if(inflater.needsDictionary()){
    
         inflater.setDictionary(dictionary.getBytes("UTF-8"));
 
         resultLength = inflater.inflate(result);
      }
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.needsInput() Method Example

Description

The java.util.zip.Inflater.needsInput() method returns true if no data remains in the input buffer. This can be used to determine if #setInput should be called in order to provide more input.

Declaration

Following is the declaration for java.util.zip.Inflater.needsInput() method.

public boolean needsInput()

Returns

true if no data remains in the input buffer.

Example

The following example shows the usage of java.util.zip.Inflater.needsInput() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0,output.length);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, 10);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result, 0 , 10);
      
      if(inflater.needsInput()){
         inflater.setInput(output, 10, compressedDataLength - resultLength);    
         resultLength += inflater.inflate(result, resultLength , result.length - resultLength);
      }

      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip.Inflater.reset() Method Example

Description

The java.util.zip.Inflater.reset() method resets inflater so that a new set of input data can be processed.

Declaration

Following is the declaration for java.util.zip.Inflater.reset() method.

public void reset()

Example

The following example shows the usage of java.util.zip.Inflater.reset() method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.reset();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
 inflater.reset();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.setDictionary(byte[] b) Method Example

Description

The java.util.zip.Inflater.setDictionary(byte[] b) method sets the preset dictionary to the given array of bytes. Should be called when inflate() returns 0 and needsDictionary() returns true indicating that a preset dictionary is required. The method getAdler() can be used to get the Adler-32 value of the dictionary needed.

Declaration

Following is the declaration for java.util.zip.Inflater.setDictionary(byte[] b) method.

public void setDictionary(byte[] b)

Parameters

  • b - the dictionary data bytes.

Example

The following example shows the usage of java.util.zip.Inflater.setDictionary(byte[] b) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
 
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setDictionary(dictionary.getBytes("UTF-8"));
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      if(inflater.needsDictionary()){
    
         inflater.setDictionary(dictionary.getBytes("UTF-8"));
 
         resultLength = inflater.inflate(result);
      }
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.setDictionary(byte[] b, int off, int len) Method Example

Description

The java.util.zip.Inflater.setDictionary(byte[] b, int off, int len) method sets the preset dictionary to the given array of bytes. Should be called when inflate() returns 0 and needsDictionary() returns true indicating that a preset dictionary is required. The method getAdler() can be used to get the Adler-32 value of the dictionary needed.

Declaration

Following is the declaration for java.util.zip.Inflater.setDictionary(byte[] b, int off, int len) method.

public void setDictionary(byte[] b, int off, int len)

Parameters

  • b - the dictionary data bytes.

  • off - the start offset of the data.

  • len - the length of the data.

Example

The following example shows the usage of java.util.zip.Inflater.setDictionary(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      String dictionary = "Welcome";
 
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
 deflater.setDictionary(dictionary.getBytes("UTF-8"),0, dictionary.length());
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, compressedDataLength);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      if(inflater.needsDictionary()){
    
         inflater.setDictionary(dictionary.getBytes("UTF-8"),0, dictionary.length());
 
         resultLength = inflater.inflate(result);
      }
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.setInput(byte[] b) Method Example

Description

The java.util.zip.Inflater.setInput(byte[] b) method sets input data for decompression. Should be called whenever needsInput() returns true indicating that more input data is required.

Declaration

Following is the declaration for java.util.zip.Inflater.setInput(byte[] b) method.

public void setInput(byte[] b)

Parameters

  • b - the input data bytes.

Example

The following example shows the usage of java.util.zip.Inflater.setInput(byte[] b) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes output :" + deflater.getTotalOut());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result);
      inflater.finished();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
      System.out.println("UnCompressed Message Checksum :" + inflater.getAdler());  
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes output :42
Compressed Message Checksum :368538129
Compressed Message length : 42
UnCompressed Message Checksum :368538129
UnCompressed Message length : 300

java.util.zip.Inflater.setInput(byte[] b, int off, int len) Method Example

Description

The java.util.zip.Inflater.setInput(byte[] b, int off, int len) method sets input data for decompression. Should be called whenever needsInput() returns true indicating that more input data is required.

Declaration

Following is the declaration for java.util.zip.Inflater.setInput(byte[] b, int off, int len) method.

public void setInput(byte[] b, int off, int len)

Parameters

  • b - the input data bytes.

  • off - he start offset of the data.

  • len - the length of the data.

Example

The following example shows the usage of java.util.zip.Inflater.setInput(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class InflaterDemo {
   public static void main(String[] args) 
      throws DataFormatException, UnsupportedEncodingException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0,output.length);
      deflater.end();

      System.out.println("Compressed Message length : " + compressedDataLength);

      // Decompress the bytes
      Inflater inflater = new Inflater();
      inflater.setInput(output, 0, 10);
      byte[] result = new byte[1024];
      int resultLength = inflater.inflate(result, 0 , 10);
      
      if(inflater.needsInput()){
         inflater.setInput(output, 10, compressedDataLength - resultLength);    
         resultLength += 
            inflater.inflate(result, resultLength , result.length - resultLength);
      }

      inflater.end();

      // Decode the bytes into a String
      message = new String(result, 0, resultLength, "UTF-8");
   
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Compressed Message length : 42
UnCompressed Message length : 300

java.util.zip - InflaterInputStream

Introduction

The java.util.zip.InflaterInputStream class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream.

Class declaration

Following is the declaration for java.util.zip.InflaterInputStream class −

public class InflaterInputStream
   extends FilterInputStream

Fields

Following are the fields for java.util.zip.InflaterInputStream class −

  • protected byte[] buf - Input buffer for decompression.

  • protected Inflater inf - Decompressor for this stream.

  • protected int len - Length of input buffer.

Constructors

S.N. Constructor & Description
1 InflaterInputStream(InputStream in)

Creates a new input stream with a default decompressor and buffer size.

2 InflaterInputStream(InputStream in, Inflater inf)

Creates a new input stream with the specified decompressor and a default buffer size.

3 InflaterInputStream(InputStream in, Inflater inf, int size)

Creates a new input stream with the specified decompressor and buffer size.

Class methods

S.N. Method & Description
1 int available()

Returns 0 after EOF has been reached, otherwise always return 1.

2 void close()

Closes this input stream and releases any system resources associated with the stream.

3 void mark(int readlimit)

Marks the current position in this input stream.

4 boolean markSupported()

Tests if this input stream supports the mark and reset methods.

5 int read()

Reads a byte of uncompressed data.

6 int read(byte[] b, int off, int len)

Reads uncompressed data into an array of bytes.

7 void reset()

Repositions this stream to the position at the time the mark method was last called on this input stream.

8 long skip(long n)

Skips specified number of bytes of uncompressed data.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterInputStream
  • java.lang.Object

java.util.zip.InflaterInputStream.available() Method Example

Description

The java.util.zip.InflaterInputStream.available() method returns 0 after EOF has been reached, otherwise always return 1.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.available() method.

public int available()
   throws IOException

Returns

zero after the end of the underlying input stream has been reached, otherwise always returns 1.

Exceptions

  • IOException - if an I/O error occurs or if this stream is already closed.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.available() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.close() Method Example

Description

The java.util.zip.InflaterInputStream.close() method closes this input stream and its underlying input stream, discarding any pending uncompressed data.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.close() method.

public int close()
   throws IOException

Exceptions

  • IOException - if an I/O error occurs.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.close() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.mark(int readlimit) Method Example

Description

The java.util.zip.InflaterInputStream.mark(int readlimit) method marks the current position in this input stream. The mark method of InflaterInputStream does nothing.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.mark(int readlimit) method.

public void mark(int readlimit)

Parameters

  • readlimit - the maximum limit of bytes that can be read before the mark position becomes invalid.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.mark(int readlimit) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.mark(0);  
      }
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.reset();  
      }
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.markSupported() Method Example

Description

The java.util.zip.InflaterInputStream.markSupported() method tests if this input stream supports the mark and reset methods. The markSupported method of InflaterInputStream returns false.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.markSupported() method.

public boolean markSupported()

Returns

a boolean indicating if this stream type supports the mark and reset methods.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.markSupported() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.mark(0);  
      }
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.reset();  
      }
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.read() Method Example

Description

The java.util.zip.InflaterInputStream.read() method reads a byte of uncompressed data. This method will block until enough input is available for decompression.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.read() method.

public int read() throws IOException

Returns

the byte read, or -1 if end of compressed input is reached.

Exceptions

  • IOException - if an I/O error occurs.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.read() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.mark(0);  
      }
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.reset();  
      }
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.read(byte[] buf, int off, int len) Method Example

Description

The java.util.zip.InflaterInputStream.read(byte[] buf, int off, int len) method reads uncompressed data into an array of bytes. If len is not zero, the method will block until some input can be decompressed; otherwise, no bytes are read and 0 is returned.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.read(byte[] buf, int off, int len) method.

public int read(byte[] buf, int off, int len)
   throws IOException

Parameters

  • buf - 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 compressed input is reached or a preset dictionary is needed.

Exceptions

  • NullPointerException - If buf is null.

  • IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than buf.length - off.

  • ZipException - if a ZIP format error has occurred.

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.read(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      inflaterInputStream.read(result, 0, result.length);

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(result,0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.reset() Method Example

Description

The java.util.zip.InflaterInputStream.reset() method repositions this stream to the position at the time the mark method was last called on this input stream. The method reset for class InflaterInputStream does nothing except throw an IOException.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.reset() method.

public void reset()

Exceptions

  • IOException - if an I/O error occurs.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.reset() method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.mark(0);  
      }
      if(inflaterInputStream.markSupported()){
         inflaterInputStream.reset();  
      }
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true

java.util.zip.InflaterInputStream.skip(long n) Method Example

Description

The java.util.zip.InflaterInputStream.skip(long n) method skips specified number of bytes of uncompressed data.

Declaration

Following is the declaration for java.util.zip.InflaterInputStream.skip(long n) method.

public long skip(long n)
   throws IOException

Parameters

  • n - the number of bytes to skip.

Returns

the actual number of bytes skipped.

Exceptions

  • IOException - if an I/O error occurs.

Example

The following example shows the usage of java.util.zip.InflaterInputStream.skip(long n) method.

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      inflaterInputStream.skip(10);
      while(inflaterInputStream.available() != 0){
         buffer.write(inflaterInputStream.read());
      }

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(buffer.toByteArray(),0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
false

java.util.zip - InflaterOutputStream

Introduction

The java.util.zip.InflaterOutputStream class implements an output stream filter for uncompressing data stored in the "deflate" compression format.

Class declaration

Following is the declaration for java.util.zip.InflaterOutputStream class −

public class InflaterOutputStream
   extends FilterOutputStream

Fields

Following are the fields for java.util.zip.InflaterOutputStream class −

  • protected byte[] buf - Output buffer for writing uncompressed data.

  • protected Inflater inf - Decompressor for this stream.

Constructors

S.N. Constructor & Description
1 InflaterOutputStream(OutputStream out)

Creates a new output stream with a default decompressor and buffer size.

2 InflaterOutputStream(OutputStream out, Inflater infl)

Creates a new output stream with the specified decompressor and a default buffer size.

3 InflaterOutputStream(OutputStream out, Inflater infl, int bufLen)

Creates a new output stream with the specified decompressor and buffer size.

Class methods

S.N. Method & Description
1 void close()

Writes remaining compressed data to the output stream and closes the underlying stream.

2 void finish()

Finishes writing uncompressed data to the output stream without closing the underlying stream.

3 void flush()

Flushes this output stream, forcing any pending buffered output bytes to be written.

4 void write(byte[] b, int off, int len)

Writes an array of bytes to the compressed output stream.

5 void write(int b)

Writes a byte to the compressed output stream.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterOutputStream
  • java.lang.Object

java.util.zip.InflaterOutputStream.close() Method Example

Description

The java.util.zip.InflaterOutputStream.close() method writes remaining compressed data to the output stream and closes the underlying stream.

Declaration

Following is the declaration for java.util.zip.InflaterOutputStream.close() method.

public void close()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.InflaterOutputStream.close() method.

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

public class InflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      InflaterOutputStream inflaterOutputStream = null;
      ByteArrayOutputStream decompressedOutputStream = null;
      decompressedOutputStream = new ByteArrayOutputStream();
      inflaterOutputStream = new InflaterOutputStream(decompressedOutputStream);
      inflaterOutputStream.write(arrayOutputStream.toByteArray());
      inflaterOutputStream.close();

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(decompressedOutputStream.toByteArray(), 300);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.InflaterOutputStream.finish() Method Example

Description

The java.util.zip.InflaterOutputStream.finish() method finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Declaration

Following is the declaration for java.util.zip.InflaterOutputStream.finish() method.

public void finish()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.InflaterOutputStream.finish() method.

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

public class InflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      InflaterOutputStream inflaterOutputStream = null;
      ByteArrayOutputStream decompressedOutputStream = null;
      decompressedOutputStream = new ByteArrayOutputStream();
      inflaterOutputStream = new InflaterOutputStream(decompressedOutputStream);
      inflaterOutputStream.write(arrayOutputStream.toByteArray());
      inflaterOutputStream.finish();
      inflaterOutputStream.close();

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(decompressedOutputStream.toByteArray(), 300);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.InflaterOutputStream.flush() Method Example

Description

The java.util.zip.InflaterOutputStream.flush() method flushes this output stream, forcing any pending buffered output bytes to be written.

Declaration

Following is the declaration for java.util.zip.InflaterOutputStream.flush() method.

public void flush()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Example

The following example shows the usage of java.util.zip.InflaterOutputStream.flush() method.

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

public class InflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      InflaterOutputStream inflaterOutputStream = null;
      ByteArrayOutputStream decompressedOutputStream = null;
      decompressedOutputStream = new ByteArrayOutputStream();
      inflaterOutputStream = new InflaterOutputStream(decompressedOutputStream);
      inflaterOutputStream.write(arrayOutputStream.toByteArray());
      inflaterOutputStream.flush();
      inflaterOutputStream.close();

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(decompressedOutputStream.toByteArray(), 300);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.InflaterOutputStream.write(byte[] b, int off, int len) Method Example

Description

The java.util.zip.InflaterOutputStream.write(byte[] b, int off, int len) method writes an array of bytes to the compressed output stream.

Declaration

Following is the declaration for java.util.zip.InflaterOutputStream.write(byte[] b, int off, int len) method.

public void write(byte[] b, int off, int len)
 throws IOException

Parameters

  • b - the data to be written.

  • off - the start offset of the data.

  • len - the length of the data.

Exceptions

  • IndexOutOfBoundsException - if off < 0, or if len < 0, or if len > b.length - off.

  • IOException - if an I/O error occurs or this stream is already closed.

  • NullPointerException - if b is null.

  • ZipException - if a compression (ZIP) format error occurs.

Example

The following example shows the usage of java.util.zip.InflaterOutputStream.write(byte[] b, int off, int len) method.

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

public class InflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      InflaterOutputStream inflaterOutputStream = null;
      ByteArrayOutputStream decompressedOutputStream = null;
      decompressedOutputStream = new ByteArrayOutputStream();
      inflaterOutputStream = new InflaterOutputStream(decompressedOutputStream);
      byte[] output = arrayOutputStream.toByteArray();
      inflaterOutputStream.write(output,0,output.length);
      inflaterOutputStream.flush();
      inflaterOutputStream.close();

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(decompressedOutputStream.toByteArray(), 300);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip.InflaterOutputStream.write(int b) Method Example

Description

The java.util.zip.InflaterOutputStream.write(int b) method writes a byte to the compressed output stream. This method will block until the byte can be written.

Declaration

Following is the declaration for java.util.zip.InflaterOutputStream.write(int b) method.

public void write(int b)
 throws IOException

Parameters

  • b - the byte to be written.

Exceptions

  • IOException - if an I/O error has occurred.

  • ZipException - if a compression (ZIP) format error occurs.

Example

The following example shows the usage of java.util.zip.InflaterOutputStream.write(int b) method.

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

public class InflaterOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream outputStream = new DeflaterOutputStream(arrayOutputStream);
      outputStream.write(input);
      outputStream.close();

      //Read and decompress the data
      InflaterOutputStream inflaterOutputStream = null;
      ByteArrayOutputStream decompressedOutputStream = null;
      decompressedOutputStream = new ByteArrayOutputStream();
      inflaterOutputStream = new InflaterOutputStream(decompressedOutputStream);
      byte[] output = arrayOutputStream.toByteArray();
      for(int i = 0; i < output.length; i++){
         inflaterOutputStream.write(output[i]);
      }
      inflaterOutputStream.close();

      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(decompressedOutputStream.toByteArray(), 300);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

Let us compile and run the above program, this will produce the following result −

Original Message length : 300
UnCompressed Message length : 300

java.util.zip - ZipEntry

Introduction

The java.util.zip.ZipEntry class is used to represent a ZIP file entry.

Class declaration

Following is the declaration for java.util.zip.ZipEntry class −

public class ZipEntry
   extends Object
      implements Cloneable

Fields

Following are the fields for java.util.zip.ZipEntry class −

  • protected byte[] buf - Output buffer for writing uncompressed data.

  • protected Inflater inf - Decompressor for this stream.

  • static int CENATT

  • static int CENATX

  • static int CENCOM

  • static int CENCRC

  • static int CENDSK

  • static int CENEXT

  • static int CENFLG

  • static int CENHDR

  • static int CENHOW

  • static int CENLEN

  • static int CENNAM

  • static int CENOFF

  • static long CENSIG

  • static int CENSIZ

  • static int CENTIM

  • static int CENVEM

  • static int CENVER

  • static int DEFLATED - Compression method for compressed (deflated) entries.

  • static int ENDCOM

  • static int ENDHDR

  • static int ENDOFF

  • static long ENDSIG

  • static int ENDSIZ

  • static int ENDSUB

  • static int ENDTOT

  • static int EXTCRC

  • static int EXTHDR

  • static int EXTLEN

  • static long EXTSIG

  • static int EXTSIZ

  • static int LOCCRC

  • static int LOCEXT

  • static int LOCFLG

  • static int LOCHDR

  • static int LOCHOW

  • static int LOCLEN

  • static int LOCNAM

  • static long LOCSIG

  • static int LOCSIZ

  • static int LOCTIM

  • static int LOCVER

  • static int STORED - Compression method for uncompressed entries.

Constructors

S.N. Constructor & Description
1 ZipEntry(String name)

Creates a new zip entry with the specified name.

2 ZipEntry(ZipEntry e)

Creates a new zip entry with fields taken from the specified zip entry.

Class methods

S.N. Method & Description
1 Object clone()

Returns a copy of this entry.

2 String getComment()

Returns the comment string for the entry, or null if none.

3 long getCompressedSize()

Returns the size of the compressed entry data, or -1 if not known.

4 long getCrc()

Returns the CRC-32 checksum of the uncompressed entry data, or -1 if not known.

5 byte[] getExtra()

Returns the extra field data for the entry, or null if none.

6 int getMethod()

Returns the compression method of the entry, or -1 if not specified.

7 String getName()

Returns the name of the entry.

8 long getSize()

Returns the uncompressed size of the entry data, or -1 if not known.

9 long getTime()

Returns the modification time of the entry, or -1 if not specified.

10 int hashCode()

Returns the hash code value for this entry.

11 boolean isDirectory()

Returns true if this is a directory entry.

12 void setComment(String comment)

Sets the optional comment string for the entry.

13 void setCrc(long crc)

Sets the CRC-32 checksum of the uncompressed entry data.

14 void setExtra(byte[] extra)

Sets the optional extra field data for the entry.

15 void setMethod(int method)

Sets the compression method for the entry.

16 void setSize(long size)

Sets the uncompressed size of the entry data.

17 void setTime(long time)

Sets the modification time of the entry.

18 String toString()

Returns a string representation of the ZIP entry.

Methods inherited

This class inherits methods from the following classes −

  • java.io.FilterOutputStream
  • java.lang.Object

java.util.zip.ZipEntry.clone() Method Example

Description

The java.util.zip.ZipEntry.clone() method returns a copy of this entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.clone() method.

public Object clone()

Returns

a clone of this instance.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.clone() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      zout.putNextEntry(new ZipEntry(SOURCE_FILE));
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            ZipEntry clonedEntry = (ZipEntry)entry.clone();
            extractFile(clonedEntry, file.getInputStream(clonedEntry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/19/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getComment() Method Example

Description

The java.util.zip.ZipEntry.getComment() method returns the comment string for the entry, or null if none.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getComment() method.

public String getComment()

Returns

the comment string for the entry, or null if none.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getComment() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setComment("This is a sample file.");
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.getComment());
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
This is a sample file. 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getCompressedSize() Method Example

Description

The java.util.zip.ZipEntry.getCompressedSize() method returns the size of the compressed entry data, or -1 if not known. In the case of a stored entry, the compressed size will be the same as the uncompressed size of the entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getCompressedSize() method.

public long getCompressedSize()

Returns

the size of the compressed entry data, or -1 if not known

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getCompressedSize() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.getCompressedSize());
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
19
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getCrc() Method Example

Description

The java.util.zip.ZipEntry.getCrc() method returns the CRC-32 checksum of the uncompressed entry data, or -1 if not known.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getCrc() method.

public long getCrc()

Returns

the CRC-32 checksum of the uncompressed entry data, or -1 if not known.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getCrc() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.getCrc());
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
463570035
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getExtra() Method Example

Description

The java.util.zip.ZipEntry.getExtra() method returns the extra field data for the entry, or null if none.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getExtra() method.

public byte[] getExtra()

Returns

the extra field data for the entry, or null if none.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getExtra() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setExtra("sample data".getBytes());
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(new String(entry.getExtra(), 0, entry.getExtra().length, "UTF-8"));
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
sample data
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getMethod() Method Example

Description

The java.util.zip.ZipEntry.getMethod() method returns the compression method of the entry, or -1 if not specified.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getMethod() method.

public int getMethod()

Returns

the compression method of the entry, or -1 if not specified.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getMethod() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setMethod(ZipEntry.DEFLATED);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.getMethod() == ZipEntry.DEFLATED ? "Deflate" : "Stored");
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Deflate
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getName() Method Example

Description

The java.util.zip.ZipEntry.getName() method returns the name of the entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getName() method.

public String getName()

Returns

the name of the entry.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getName() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getSize() Method Example

Description

The java.util.zip.ZipEntry.getSize() method returns the uncompressed size of the entry data, or -1 if not known.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getSize() method.

public long getSize()

Returns

the uncompressed size of the entry data, or -1 if not known.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getSize() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.getTime() Method Example

Description

The java.util.zip.ZipEntry.getTime() method returns the modification time of the entry, or -1 if not specified.

Declaration

Following is the declaration for java.util.zip.ZipEntry.getTime() method.

public long getTime()

Returns

the modification time of the entry, or -1 if not specified.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.getTime() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.hashCode() Method Example

Description

The java.util.zip.ZipEntry.hashCode() method returns the hash code value for this entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.hashCode() method.

public int hashCode()

Returns

a hash code value for this object.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.hashCode() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime()));
            System.out.println(entry.hashCode());
 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
-1161923440
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.isDirectory() Method Example

Description

The java.util.zip.ZipEntry.isDirectory() method returns true if this is a directory entry. A directory entry is defined to be one whose name ends with a '/'.

Declaration

Following is the declaration for java.util.zip.ZipEntry.isDirectory() method.

public boolean isDirectory()

Returns

true if this is a directory entry.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.isDirectory() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime()));
            System.out.println(entry.isDirectory());
 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
false
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.setComment(String comment) Method Example

Description

The java.util.zip.ZipEntry.setComment(String comment) method sets the optional comment string for the entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.setComment(String comment) method.

public void setComment(String comment)

Parameters

  • comment - the comment string.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.setComment(String comment) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setComment("This is a sample file.");
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.getComment());
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
This is a sample file. 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.setCrc(long crc) Method Example

Description

The java.util.zip.ZipEntry.setCrc(long crc) method sets the CRC-32 checksum of the uncompressed entry data.

Declaration

Following is the declaration for java.util.zip.ZipEntry.setCrc(long crc) method.

public void setCrc(long crc)

Parameters

  • IllegalArgumentException - if the specified CRC-32 value is less than 0 or greater than 0xFFFFFFFF.

Exceptions

  • crc - the CRC-32 value.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.setCrc(long crc) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      ZipOutputStream zout = new ZipOutputStream(fout);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      byte[] buffer = new byte[1024];
      fin.read(buffer, 0, buffer.length);
      
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);      
      CRC32 crc = new CRC32();
      zipEntry.setSize((long) buffer.length);
      crc.reset();
      crc.update(buffer);
      zipEntry.setCrc(crc.getValue());
 zipEntry.setTime(System.currentTimeMillis());
      zout.putNextEntry(zipEntry);
      
      zout.write(buffer, 0, buffer.length);

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 1024 Modified on 05/20/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.setExtra(byte[] extra) Method Example

Description

The java.util.zip.ZipEntry.setExtra(byte[] extra) method sets the optional extra field data for the entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.setExtra(byte[] extra) method.

public void setExtra(byte[] extra)

Parameters

  • extra - the extra field data bytes.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.setExtra(byte[] extra) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setExtra("sample data".getBytes());
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(new String(entry.getExtra(), 0, entry.getExtra().length, "UTF-8"));
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
sample data
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.setMethod(int method) Method Example

Description

The java.util.zip.ZipEntry.setMethod(int method) method sets the compression method for the entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.setMethod(int method) method.

public void setMethod(int method)

Parameters

  • method - the compression method, either STORED or DEFLATED.

Exceptions

  • IllegalArgumentException - if the specified compression method is invalid.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.setMethod(int method) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setMethod(ZipEntry.DEFLATED);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.getMethod() == ZipEntry.DEFLATED ? "Deflate" : "Stored");
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Deflate
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.setSize(long size) Method Example

Description

The java.util.zip.ZipEntry.setSize(long size) method sets the uncompressed size of the entry data.

Declaration

Following is the declaration for java.util.zip.ZipEntry.setSize(long size) method.

public void setSize(long size)

Parameters

  • size - the uncompressed size in bytes.

Exceptions

  • IllegalArgumentException - if the specified size is less than 0, is greater than 0xFFFFFFFF when ZIP64 format is not supported, or is less than 0 when ZIP64 is supported.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.setSize(long size) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      ZipOutputStream zout = new ZipOutputStream(fout);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      byte[] buffer = new byte[1024];
      fin.read(buffer, 0, buffer.length);
      
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);      
      CRC32 crc = new CRC32();
      zipEntry.setSize((long) buffer.length);
      crc.reset();
      crc.update(buffer);
      zipEntry.setCrc(crc.getValue());
      zout.putNextEntry(zipEntry);
      
      zout.write(buffer, 0, buffer.length);

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 1024 Modified on 05/20/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.setTime(long time) Method Example

Description

The java.util.zip.ZipEntry.setTime(long time) method sets the modification time of the entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.setTime(long time) method.

public void setTime(long time)

Parameters

  • time - the entry modification time in number of milliseconds since the epoch.

Exceptions

  • IllegalArgumentException - if the specified size is less than 0, is greater than 0xFFFFFFFF when ZIP64 format is not supported, or is less than 0 when ZIP64 is supported.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.setTime(long time) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      ZipOutputStream zout = new ZipOutputStream(fout);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      byte[] buffer = new byte[1024];
      fin.read(buffer, 0, buffer.length);
      
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);      
      CRC32 crc = new CRC32();
      zipEntry.setSize((long) buffer.length);
      crc.reset();
      crc.update(buffer);
      zipEntry.setCrc(crc.getValue());
 zipEntry.setTime(System.currentTimeMillis());
      zout.putNextEntry(zipEntry);
      
      zout.write(buffer, 0, buffer.length);

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 1024 Modified on 05/20/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipEntry.toString() Method Example

Description

The java.util.zip.ZipEntry.toString() method returns a string representation of the ZIP entry.

Declaration

Following is the declaration for java.util.zip.ZipEntry.toString() method.

public String toString()

Parameters

  • method - the compression method, either STORED or DEFLATED.

Exceptions

  • IllegalArgumentException - if the specified compression method is invalid.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipEntry.toString() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipEntryDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);      
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(entry.toString());
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
D:\test\Hello.txt
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip - ZipFile

Introduction

The java.util.zip.ZipFile class is used to read entries from a zip file.

Class declaration

Following is the declaration for java.util.zip.ZipFile class −

public class ZipFile
   extends Object
      implements Closeable

Fields

Following are the fields for java.util.zip.ZipFile class −

  • static int CENATT

  • static int CENATX

  • static int CENCOM

  • static int CENCRC

  • static int CENDSK

  • static int CENEXT

  • static int CENFLG

  • static int CENHDR

  • static int CENHOW

  • static int CENLEN

  • static int CENNAM

  • static int CENOFF

  • static long CENSIG

  • static int CENSIZ

  • static int CENTIM

  • static int CENVEM

  • static int CENVER

  • static int ENDCOM

  • static int ENDHDR

  • static int ENDOFF

  • static long ENDSIG

  • static int ENDSIZ

  • static int ENDSUB

  • static int ENDTOT

  • static int EXTCRC

  • static int EXTHDR

  • static int EXTLEN

  • static long EXTSIG

  • static int EXTSIZ

  • static int LOCCRC

  • static int LOCEXT

  • static int LOCFLG

  • static int LOCHDR

  • static int LOCHOW

  • static int LOCLEN

  • static int LOCNAM

  • static long LOCSIG

  • static int LOCSIZ

  • static int LOCTIM

  • static int LOCVER

  • static int OPEN_DELETE - Mode flag to open a zip file and mark it for deletion.

  • static int OPEN_READ - Mode flag to open a zip file for reading.

Constructors

S.N. Constructor & Description
1 ZipFile(File file)

Opens a ZIP file for reading given the specified File object.

2 ZipFile(File file, Charset charset)

Opens a ZIP file for reading given the specified File object.

3 ZipFile(File file, int mode)

Opens a new ZipFile to read from the specified File object in the specified mode.

4 ZipFile(File file, int mode, Charset charset)

Opens a new ZipFile to read from the specified File object in the specified mode.

5 ZipFile(String name)

Opens a zip file for reading.

6 ZipFile(String name, Charset charset)

Opens a zip file for reading.

Class methods

S.N. Method & Description
1 void close()

Closes the ZIP file.

2 Enumeration<? extends ZipEntry> entries()

Returns an enumeration of the ZIP file entries.

3 String getComment()

Returns the zip file comment, or null if none.

4 ZipEntry getEntry(String name)

Returns the zip file entry for the specified name, or null if not found.

5 InputStream getInputStream(ZipEntry entry)

Returns an input stream for reading the contents of the specified zip file entry.

6 String getName()

Returns the path name of the ZIP file.

7 int size()

Returns the number of entries in the ZIP file.

Methods inherited

This class inherits methods from the following classes −

  • Java.lang.Object

java.util.zip.ZipFile.close() Method Example

Description

The java.util.zip.ZipFile.close() method closes the ZIP file. Closing this ZIP file will close all of the input streams previously returned by invocations of the getInputStream method.

Declaration

Following is the declaration for java.util.zip.ZipFile.close() method.

public void close()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.close() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipFile.entries() Method Example

Description

The java.util.zip.ZipFile.entries() method returns an enumeration of the ZIP file entries.

Declaration

Following is the declaration for java.util.zip.ZipFile.entries() method.

public Enumeration<? extends ZipEntry> entries()

Returns

an enumeration of the ZIP file entries.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.entries() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipFile.getComment() Method Example

Description

The java.util.zip.ZipFile.getComment() method returns the zip file comment, or null if none.

Declaration

Following is the declaration for java.util.zip.ZipFile.getComment() method.

public String getComment()

Returns

the comment string for the zip file, or null if none.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.getComment() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      zout.setComment("This is a sample file.");
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.println("Iterating over zip file : " + TARGET_FILE);
      try { 
         final Enumeration<? extends ZipEntry> entries = file.entries(); 
         while (entries.hasMoreElements()) { 
            final ZipEntry entry = entries.nextElement(); 
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
                  new Date(entry.getTime())); 
            System.out.println(file.getComment());
            extractFile(entry, file.getInputStream(entry)); 
         } 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Iterating over zip file : D:\test\Hello.zip
File: D:\test\Hello.txt Size 19 Modified on 05/20/17
This is a sample file.
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipFile.getEntry(String name) Method Example

Description

The java.util.zip.ZipFile.getEntry(String name) method returns the zip file entry for the specified name, or null if not found.

Declaration

Following is the declaration for java.util.zip.ZipFile.getEntry(String name) method.

public ZipEntry getEntry(String name)

Parameters

  • name - the name of the entry.

Returns

the zip file entry, or null if not found.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.getEntry(String name) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setComment("This is a sample file.");
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
    
      try { 
         ZipEntry entry = file.getEntry(SOURCE_FILE);
         if(entry != null){
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
               new Date(entry.getTime()));
            extractFile(entry, file.getInputStream(entry)); 
         }
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Size 1024 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipFile.getInputStream(ZipEntry entry) Method Example

Description

The java.util.zip.ZipFile.getInputStream(ZipEntry entry) method returns an input stream for reading the contents of the specified zip file entry.

Declaration

Following is the declaration for java.util.zip.ZipFile.getInputStream(ZipEntry entry) method.

public InputStream getInputStream(ZipEntry entry)
   throws IOException

Parameters

  • entry - the zip file entry.

Returns

the input stream for reading the contents of the specified zip file entry.

Exceptions

  • ZipException - if a ZIP format error has occurred.

  • IOException - if an I/O error has occurred.

  • IllegalStateException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.getInputStream(ZipEntry entry) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setComment("This is a sample file.");
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
    
      try { 
         ZipEntry entry = file.getEntry(SOURCE_FILE);
         if(entry != null){
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
               new Date(entry.getTime()));
            extractFile(entry, file.getInputStream(entry)); 
         }
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Size 1024 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipFile.getName() Method Example

Description

The java.util.zip.ZipFile.getName() method returns the path name of the ZIP file.

Declaration

Following is the declaration for java.util.zip.ZipFile.getName() method.

public String getName()

Returns

the path name of the ZIP file.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.getName() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setComment("This is a sample file.");
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.printf("Zip File: %s, Contains %d file(s). %n",file.getName(), file.size()); 
      try { 
         ZipEntry entry = file.getEntry(SOURCE_FILE);
         if(entry != null){
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
               new Date(entry.getTime()));
            extractFile(entry, file.getInputStream(entry)); 
         }
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1024 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipFile.size() Method Example

Description

The java.util.zip.ZipFile.size() method returns the number of entries in the ZIP file.

Declaration

Following is the declaration for java.util.zip.ZipFile.size() method.

public int size()

Returns

the number of entries in the ZIP file.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipFile.size() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zipEntry.setComment("This is a sample file.");
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      final ZipFile file = new ZipFile(TARGET_FILE); 
      System.out.printf("Zip File: %s, Contains %d file(s). %n",file.getName(), file.size()); 
      try { 
         ZipEntry entry = file.getEntry(SOURCE_FILE);
         if(entry != null){
            System.out.printf("File: %s Size %d Modified on %TD %n", 
               entry.getName(), entry.getSize(), 
               new Date(entry.getTime()));
            extractFile(entry, file.getInputStream(entry)); 
         }
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); 
      } 
      finally { 
         file.close(); 
      }
   }

   private static void extractFile(final ZipEntry entry, InputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1024 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip - ZipInputStream

Introduction

The java.util.zip.ZipInputStream class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.

Class declaration

Following is the declaration for java.util.zip.ZipInputStream class −

public class ZipInputStream
   extends InflaterInputStream

Fields

Following are the fields for java.util.zip.ZipInputStream class −

  • static int CENATT

  • static int CENATX

  • static int CENCOM

  • static int CENCRC

  • static int CENDSK

  • static int CENEXT

  • static int CENFLG

  • static int CENHDR

  • static int CENHOW

  • static int CENLEN

  • static int CENNAM

  • static int CENOFF

  • static long CENSIG

  • static int CENSIZ

  • static int CENTIM

  • static int CENVEM

  • static int CENVER

  • static int ENDCOM

  • static int ENDHDR

  • static int ENDOFF

  • static long ENDSIG

  • static int ENDSIZ

  • static int ENDSUB

  • static int ENDTOT

  • static int EXTCRC

  • static int EXTHDR

  • static int EXTLEN

  • static long EXTSIG

  • static int EXTSIZ

  • static int LOCCRC

  • static int LOCEXT

  • static int LOCFLG

  • static int LOCHDR

  • static int LOCHOW

  • static int LOCLEN

  • static int LOCNAM

  • static long LOCSIG

  • static int LOCSIZ

  • static int LOCTIM

  • static int LOCVER

Constructors

S.N. Constructor & Description
1 ZipInputStream(InputStream in)

Creates a new ZIP input stream.

2 ZipInputStream(InputStream in, Charset charset)

Creates a new ZIP input stream.

Class methods

S.N. Method & Description
1 int available()

Returns 0 after EOF has reached for the current entry data, otherwise always return 1.

2 void close()

Closes this input stream and releases any system resources associated with the stream.

3 void closeEntry()

Closes the current ZIP entry and positions the stream for reading the next entry.

4 ZipEntry getNextEntry()

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

5 int read(byte[] b, int off, int len)

Reads from the current ZIP entry into an array of bytes.

6 long skip(long n)

Skips specified number of bytes in the current ZIP entry.

Methods inherited

This class inherits methods from the following classes −

  • java.util.zip.InflaterInputStream
  • java.io.FilterInputStream
  • java.lang.Object

java.util.zip.ZipInputStream.available() Method Example

Description

The java.util.zip.ZipInputStream.available() method returns 0 after EOF has reached for the current entry data, otherwise always return 1.

Declaration

Following is the declaration for java.util.zip.ZipInputStream.available() method.

public int available()
   throws IOException

Returns

1 before EOF and 0 after EOF has reached for current entry.

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipInputStream.available() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipInputStream.close() Method Example

Description

The java.util.zip.ZipInputStream.close() method closes this input stream and releases any system resources associated with the stream.

Declaration

Following is the declaration for java.util.zip.ZipInputStream.close() method.

public void close()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipInputStream.close() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipInputStream.closeEntry() Method Example

Description

The java.util.zip.ZipInputStream.closeEntry() method closes the current ZIP entry and positions the stream for reading the next entry.

Declaration

Following is the declaration for java.util.zip.ZipInputStream.closeEntry() method.

public void closeEntry()
   throws IOException

Exceptions

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipInputStream.closeEntry() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipInputStream.getNextEntry() Method Example

Description

The java.util.zip.ZipInputStream.getNextEntry() method reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Declaration

Following is the declaration for java.util.zip.ZipInputStream.getNextEntry() method.

public ZipEntry getNextEntry()
   throws IOException

Returns

the next ZIP file entry, or null if there are no more entries.

Exceptions

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipInputStream.getNextEntry() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) Method Example

Description

The java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method 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.

Declaration

Following is the declaration for java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method.

public int read(byte[] buf, int off, int len)
   throws IOException

Parameters

  • buf - 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 stream is reached.

Exceptions

  • NullPointerException - If buf is null.

  • IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than buf.length - off.

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipInputStream.skip(long n) Method Example

Description

The java.util.zip.ZipInputStream.skip(long n) method skips specified number of bytes in the current ZIP entry.

Declaration

Following is the declaration for java.util.zip.ZipInputStream.skip(long n) method.

public long skip(long n)
   throws IOException

Parameters

  • n - the number of bytes to skip.

Returns

the actual number of bytes skipped.

Exceptions

  • IllegalArgumentException - If n < 0.

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipInputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         final byte[] buf = new byte[1024]; 
         int read = 0; 
         int length; 
         is.skip(0);
         while ((length = is.read(buf, 0, buf.length)) >= 0) { 
            fos.write(buf, 0, length); 
         } 
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

File: D:\test\Hello.txt Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip - ZipOutputStream

Introduction

The java.util.zip.ZipOutputStream class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.

Class declaration

Following is the declaration for java.util.zip.ZipOutputStream class −

public class ZipOutputStream
   extends DeflaterOutputStream

Fields

Following are the fields for java.util.zip.ZipOutputStream class −

  • static int CENATT

  • static int CENATX

  • static int CENCOM

  • static int CENCRC

  • static int CENDSK

  • static int CENEXT

  • static int CENFLG

  • static int CENHDR

  • static int CENHOW

  • static int CENLEN

  • static int CENNAM

  • static int CENOFF

  • static long CENSIG

  • static int CENSIZ

  • static int CENTIM

  • static int CENVEM

  • static int CENVER

  • static int DEFLATED - Compression method for compressed (DEFLATED) entries.

  • static int ENDCOM

  • static int ENDHDR

  • static int ENDOFF

  • static long ENDSIG

  • static int ENDSIZ

  • static int ENDSUB

  • static int ENDTOT

  • static int EXTCRC

  • static int EXTHDR

  • static int EXTLEN

  • static long EXTSIG

  • static int EXTSIZ

  • static int LOCCRC

  • static int LOCEXT

  • static int LOCFLG

  • static int LOCHDR

  • static int LOCHOW

  • static int LOCLEN

  • static int LOCNAM

  • static long LOCSIG

  • static int LOCSIZ

  • static int LOCTIM

  • static int LOCVER

  • static int STORED - Compression method for uncompressed (STORED) entries.

Constructors

S.N. Constructor & Description
1 ZipOutputStream(OutputStream out)

Creates a new ZIP output stream.

2 ZipOutputStream(OutputStream out, Charset charset)

Creates a new ZIP output stream.

Class methods

S.N. Method & Description
1 void close()

Closes the ZIP output stream as well as the stream being filtered.

2 void closeEntry()

Closes the current ZIP entry and positions the stream for writing the next entry.

3 void finish()

Finishes writing the contents of the ZIP output stream without closing the underlying stream.

4 void putNextEntry(ZipEntry e)

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

5 void setComment(String comment)

Sets the ZIP file comment.

6 void setLevel(int level)

Sets the compression level for subsequent entries which are DEFLATED.

7 void setMethod(int method)

Sets the default compression method for subsequent entries.

8 void write(byte[] b, int off, int len)

Writes an array of bytes to the current ZIP entry data.

Methods inherited

This class inherits methods from the following classes −

  • java.util.zip.DeflaterOutputStream
  • java.io.FilterOutputStream
  • java.lang.Object

java.util.zip.ZipOutputStream.close() Method Example

Description

The java.util.zip.ZipOutputStream.close() method closes the ZIP output stream as well as the stream being filtered.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.close() method.

public void close()
   throws IOException

Exceptions

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.close() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.closeEntry() Method Example

Description

The java.util.zip.ZipOutputStream.closeEntry() method closes the current ZIP entry and positions the stream for writing the next entry.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.closeEntry() method.

public void closeEntry()
   throws IOException

Exceptions

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.closeEntry() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.finish() Method Example

Description

The java.util.zip.ZipOutputStream.finish() method finishes writing the contents of the ZIP output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.finish() method.

public void finish()
   throws IOException

Exceptions

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.finish() method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      zout.finish();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.putNextEntry(ZipEntry e) Method Example

Description

The java.util.zip.ZipOutputStream.putNextEntry(ZipEntry e) method begins writing a new ZIP file entry and positions the stream to the start of the entry data. Closes the current entry if still active. The default compression method will be used if no compression method was specified for the entry, and the current time will be used if the entry has no set modification time.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.putNextEntry(ZipEntry e) method.

public void putNextEntry(ZipEntry e)
   throws IOException

Parameters

  • e - the ZIP entry to be written.

Exceptions

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.putNextEntry(ZipEntry e) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      zout.finish();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.setComment(String comment) Method Example

Description

The java.util.zip.ZipOutputStream.setComment(String comment) method sets the ZIP file comment.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.setComment(String comment) method.

public void setComment(String comment)

Parameters

  • comment - the comment string.

Exceptions

  • IllegalArgumentException - if the length of the specified ZIP file comment is greater than 0xFFFF bytes.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.setComment(String comment) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      zout.setComment("This is a sample comment.");
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      zout.finish();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         System.out.println(file.getComment());
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
This is a sample comment.
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.setLevel(int level) Method Example

Description

The java.util.zip.ZipOutputStream.setLevel(int level) method sets the compression level for subsequent entries which are DEFLATED. The default setting is DEFAULT_COMPRESSION.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.setLevel(int level) method.

public void setLevel(int level)

Parameters

  • level - the compression level (0-9).

Exceptions

  • IllegalArgumentException - if the compression level is invalid.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.setLevel(int level) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.util.zip.Deflater;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);
      zout.setLevel(Deflater.DEFAULT_COMPRESSION);
      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      zout.finish();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.setMethod(int method) Method Example

Description

The java.util.zip.ZipOutputStream.setMethod(int method) method sets the default compression method for subsequent entries. This default will be used whenever the compression method is not specified for an individual ZIP file entry, and is initially set to DEFLATED.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.setMethod(int method) method.

public void setMethod(int method)

Parameters

  • method - the default compression method.

Exceptions

  • IllegalArgumentException - if the compression method is invalid.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.setMethod(int method) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);
      zout.setMethod(ZipOutputStream.DEFLATED);
      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      zout.finish();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip.ZipOutputStream.write(byte[] buf, int off, int len) Method Example

Description

The java.util.zip.ZipOutputStream.write(byte[] buf, int off, int len) method writes an array of bytes to the current ZIP entry data. This method will block until all the bytes are written.

Declaration

Following is the declaration for java.util.zip.ZipOutputStream.write(byte[] buf, int off, int len) method.

public void write(byte[] buf, int off, int len)
   throws IOException

Parameters

  • buf - the buffer into which the data to be written.

  • off - the start offset in the destination array b.

  • len - the number of bytes to be written.

Exceptions

  • ZipException - if a ZIP file error has occurred.

  • IOException - if an I/O error has occurred.

Pre-requisite

Create a file Hello.txt in D:> test > directory with the following content.

This is an example.

Example

The following example shows the usage of java.util.zip.ZipOutputStream.write(byte[] buf, int off, int len) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {
   private static String SOURCE_FILE = "D:\\test\\Hello.txt";
   private static String TARGET_FILE = "D:\\test\\Hello.zip";

   public static void main(String[] args) {
      try {
         createZipFile();
         readZipFile();
      } catch(IOException ioe) {
         System.out.println("IOException : " + ioe);
      }
   }

   private static void createZipFile() throws IOException{
      FileOutputStream fout = new FileOutputStream(TARGET_FILE);
      CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
      ZipOutputStream zout = new ZipOutputStream(checksum);

      FileInputStream fin = new FileInputStream(SOURCE_FILE);
      ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
      zout.putNextEntry(zipEntry);
      int length;
      byte[] buffer = new byte[1024];
      while((length = fin.read(buffer)) > 0) {
         zout.write(buffer, 0, length);
      }

      zout.closeEntry();
      zout.finish();
      fin.close();
      zout.close();
   }

   private static void readZipFile() throws IOException{
      ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); 

      ZipEntry entry;
      while((entry = zin.getNextEntry())!=null){
         System.out.printf("File: %s Modified on %TD %n", 
         entry.getName(), new Date(entry.getTime()));
         extractFile(entry, zin); 
         System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
         zin.closeEntry();
      }
      zin.close();
   }

   private static void extractFile(final ZipEntry entry, ZipInputStream is) 
      throws IOException {
      FileOutputStream fos = null; 
      try { 
         fos = new FileOutputStream(entry.getName()); 
         while(is.available() != 0){
            fos.write(is.read()); 
         }
      } catch (IOException ioex) { 
         fos.close(); 
      } 
   }
}

Let us compile and run the above program, this will produce the following result −

Zip File: D:\test\Hello.zip, Contains 1 file(s). 
File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 
Zip file D:\test\Hello.txt extracted successfully.

java.util.zip - Interface

Introduction

The java.util.zip Interface contains the interface which is used to obtain checksum related information about classes and objects.

Interface Summary

S.N. Interface & Description
1

Checksum

An interface representing a data checksum.

java.util.zip - Exceptions

Introduction

The java.util.zip Exceptions contains the exceptions which can occur during zip/unzip operations.

Interface Summary

S.N. Exception & Description
1

DataFormatException

Signals that a data format error has occurred.

2

ZipException

Signals that a Zip exception of some sort has occurred.

java.util.zip - Error

Introduction

The java.util.zip Error contains the error which can occur during zip/unzip operations.

Interface Summary

S.N. Error & Description
1

ZipError

Signals that an unrecoverable error has occurred.



Advertisements