Home  >  Core Java

Example of CheckedOutputStream and CheckedInputStream in Java

By Arvind Rai, April 13, 2013
CheckedOutputStream is the output stream that maintains the checksum while writing the data. CheckedOutputStream helps to check integrity of data after writing. CheckedInputStream checks the checksum after reading the input data. It is used to check integrity of data after reading.
ZipChecksumTest.java
package com.concretepage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 ZipChecksumTest {
    public static void main(String... args) throws IOException {
        String source="D:/page/file.txt";
        File sfile= new File(source);
        String dest="D:/page/file.zip";
        File dfile= new File(dest);
        FileInputStream fis= new FileInputStream(sfile);
        FileOutputStream fos= new FileOutputStream(dfile);
        //used to check checksum after writing data
        CheckedOutputStream csum = new CheckedOutputStream(fos, new Adler32());
        ZipOutputStream zos= new ZipOutputStream(csum);
        ZipEntry ze= new ZipEntry(source);
        //begins writing a new zip file and sets the the position to the start of data
        zos.putNextEntry(ze);
        byte[] buf = new byte[1024];
        int len;
        while((len=fis.read(buf))>0){
            zos.write(buf, 0, len);
        }
        fis.close();
        zos.close();
        System.out.println("checksum after writing zip:"+csum.getChecksum().getValue());
        // directory to read zip file and to write extracted file
        String dir="D:/page/";
        // read zip file as input stream
        InputStream is= new FileInputStream(dir+"file.zip");
        //used to check checksum after reading data
        CheckedInputStream chksum = new CheckedInputStream(is, new Adler32());
        //zip is read by ZipInputStream
        ZipInputStream zis= new ZipInputStream(chksum);
        // now write zip file in extracted file
        byte[] buff = new byte[1024];
        while((ze=zis.getNextEntry())!=null){
            // get file name
            fos= new FileOutputStream(ze.getName());
            int l=0;
            // write buffer to file
            while((l=zis.read(buff))>0){
                fos.write(buff,0, l);
            }
        }
        zis.close();
        System.out.println("checksum after reading zip:"+csum.getChecksum().getValue());
    }
}
Output
checksum after writing zip:2301499827
checksum after reading zip:2301499827 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us