Java by API/java.util.zip/Checksum — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 14:21, 31 мая 2010
Содержание
Checksum: getValue()
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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(args[0]);
System.out.println(args[0] + ":\t" + getCRC32(fin));
fin.close();
}
public static long getCRC32(InputStream in) throws IOException {
Checksum cs = new CRC32();
for (int b = in.read(); b != -1; b = in.read()) {
cs.update(b);
}
return cs.getValue();
}
}
Checksum: reset()
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();
}
}
Checksum: update(int b)
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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(args[0]);
System.out.println(args[0] + ":\t" + getCRC32(fin));
fin.close();
}
public static long getCRC32(InputStream in) throws IOException {
Checksum cs = new CRC32();
for (int b = in.read(); b != -1; b = in.read()) {
cs.update(b);
}
return cs.getValue();
}
}
implements Checksum
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;
}
}