CheckSum 类
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.zip.CRC32;
public class CheckSum {
public static void main(String[] args) {
try {
new CheckSum().checksum();
} catch (Exception e) {
e.printStackTrace();
}
}
public void checksum() throws Exception {
CRC32 crc32 = new CRC32();
Charset encoding = Charset.forName("UTF-8");
Reader reader = null;
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("xxxx.txt");
reader = new BomStrippingReader(new InputStreamReader(inputStream, encoding));
String line;
while((line = readLine(reader)) != null) {
crc32.update(trimLineBreak(line).getBytes("UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}
System.out.println((int)crc32.getValue());;
}
public String readLine(Reader reader) {
try {
StringBuilder line = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
line.append(ch);
if (ch == '\n') {
break;
}
}
if (line.length() == 0) {
return null;
}
return line.toString();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public String trimLineBreak(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
while (buf.length() > 0 && isLineBreakCharacter(buf.charAt(buf.length() - 1))) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
public boolean hasLength(String str) {
return str != null && str.length() > 0;
}
private boolean isLineBreakCharacter(char ch) {
return '\n' == ch || '\r' == ch;
}
}
BomStrippingReader
import java.io.FilterReader;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
public class BomStrippingReader extends FilterReader {
private static final int EMPTY_STREAM = -1;
private static final char BOM = '\ufeff';
/**
* Creates a new BOM-stripping reader.
*
* @param in a Reader object providing the underlying stream.
* @throws NullPointerException if <code>in</code> is <code>null</code>
*/
public BomStrippingReader(Reader in) throws IOException {
super(new PushbackReader(in));
PushbackReader pbr = (PushbackReader) this.in;
int firstChar = pbr.read();
if (firstChar != EMPTY_STREAM && firstChar != BOM) {
pbr.unread(firstChar);
}
}
}