Java Tutorial/File/Checksum

Материал из Java эксперт
Перейти к: навигация, поиск

A single checksum calculation for multiple files

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream; import java.util.zip.Checksum; /**

* Perform a single checksum calculation for multiple files
*
* @author 
* @version $Id$
*/

public class MultiFileChecksumHelper {

   public static long getChecksum(File[] files)
   {
       CheckedInputStream cis = null;
       FileInputStream is = null;
       Checksum checksum = new Adler32();
       byte[] tempBuf = new byte[128];
       
       for ( int i = 0; i < files.length && files[i] != null && files[i].exists() && files[i].isFile(); i++ )
       {
           try 
           {
               is = new FileInputStream(files[i]);
               cis = new CheckedInputStream(is, checksum);
               while (cis.read(tempBuf) >= 0) {}                
           }
           catch (Exception e)
           {
               throw new RuntimeException(e);
           }
           finally
           {
               if (cis != null)
               {
                   try
                   {
                       cis.close();
                   }
                   catch (IOException ioe) {}
                   cis = null;
               }
               if (is != null)
               {
                   try
                   {
                       is.close();
                   }
                   catch (IOException ioe) {}
                   is = null;
               }
           }
       }
       return checksum.getValue();
   }

}</source>





Calculating the Checksum of a Byte Array (Compute Adler-32 checksum)

   <source lang="java">

import java.util.zip.Adler32; import java.util.zip.Checksum; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = "some data".getBytes();
   
   Checksum checksumEngine = new Adler32();
   checksumEngine.update(bytes, 0, bytes.length);
   long checksum = checksumEngine.getValue();
 }

}</source>





Calculating the Checksum of a File

   <source lang="java">

import java.io.FileInputStream; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream; public class Main {

 public static void main(String[] argv) throws Exception {
   CheckedInputStream cis = new CheckedInputStream(new FileInputStream("filename"), new Adler32());
   byte[] tempBuf = new byte[128];
   while (cis.read(tempBuf) >= 0) {
   }
   long checksum = cis.getChecksum().getValue();
 }

}</source>





Check sum for an InputStream

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream;


/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* implements checksum related utilities
*
* @author 
* @version $Id: ChecksumHelper.java 516448 2007-03-09 16:25:47Z ate $
*/

final class ChecksumHelper {

   public static long getChecksum(InputStream is)
   {
       CheckedInputStream cis = null;        
       long checksum = 0;
       try 
       {
           cis = new CheckedInputStream(is, new Adler32());
           byte[] tempBuf = new byte[128];
           while (cis.read(tempBuf) >= 0) 
           {
           }
           checksum = cis.getChecksum().getValue();
       } 
       catch (IOException e) 
       {
           checksum = 0;
       }
       finally
       {
           if (cis != null)
           {
               try
               {
                   cis.close();
               }
               catch (IOException ioe)
               {                    
               }
           }
       }
       return checksum;
   }

}</source>





Compressing Streams: File Summer

   <source lang="java">

import java.io.FileInputStream; import java.io.IOException; import java.util.zip.CRC32; import java.util.zip.Checksum; public class Main {

 public static void main(String[] args) throws IOException {
   FileInputStream fin = new FileInputStream("a.zip");
   Checksum cs = new CRC32();
   for (int b = fin.read(); b != -1; b = fin.read()) {
     cs.update(b);
   }
   System.out.println(cs.getValue());
   fin.close();
 }

}</source>





Compressing Streams: Parity Checksum

   <source lang="java">

import java.util.zip.Checksum; public class ParityChecksum implements Checksum {

 long checksum = 0;
 public void update(int b) {
   int numOneBits = 0;
   for (int i = 1; i < 256; i *= 2) {
     if ((b & i) != 0)
       numOneBits++;
   }
   checksum = (checksum + numOneBits) % 2;
 }
 public void update(byte data[], int offset, int length) {
   for (int i = offset; i < offset + length; i++) {
     this.update(data[i]);
   }
 }
 public long getValue() {
   return checksum;
 }
 public void reset() {
   checksum = 0;
 }

}</source>





Compute CRC-32 checksum

   <source lang="java">

import java.util.zip.CRC32; import java.util.zip.Checksum; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] bytes = "some data".getBytes();
   // Compute Adler-32 checksum
   Checksum checksumEngine = new CRC32();
   checksumEngine.update(bytes, 0, bytes.length);
   long checksum = checksumEngine.getValue();
   checksumEngine.reset();
 }

}</source>





The java.util.zip package can be used to create a checksum.

   <source lang="java">

import java.io.BufferedInputStream; import java.io.FileInputStream; import java.util.Arrays; import java.util.zip.CRC32; public class Main {

 public static void main(String[] args) throws Exception{
   BufferedInputStream is = new BufferedInputStream(new FileInputStream("a.exe"));
   byte[] bytes = new byte[1024];
   int len = 0;
   while ((len = is.read(bytes)) >= 0) {
     new CRC32().update(bytes, 0, len);
   }
   is.close();
   System.out.println(Arrays.toString(bytes));
 }

}</source>