public class TestNIO {
public static void main(String[] args) throws IOException {
long re = checkSumMapperFile(null);
System.out.println(re);
System.out.println(checkSumInputStream(null));
System.out.println(checkSumRandomAccess(null));
}

public static long checkSumMapperFile(String fileName) throws IOException{
long s = System.currentTimeMillis();
FileInputStream file = new FileInputStream("src\\chapter1\\t2.txt");
FileChannel channel = file.getChannel();//NIO
int len = (int) channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, len);
//CRC32 校验文件,查看破损等等
CRC32 c = new CRC32();
for (int i = 0; i < len; i++) {
int c1 = buffer.get(i);
c.update(c1);
}
file.close();
long e = System.currentTimeMillis();
System.out.println("耗时:"+(e-s)+"ms");
return c.getValue();
}

public static long checkSumInputStream(String fileName) throws IOException{
long s = System.currentTimeMillis();
FileInputStream file = new FileInputStream("src\\chapter1\\t2.txt");

//CRC32 校验文件,查看破损等等
CRC32 c = new CRC32();
int c1;
while ((c1=file.read()) != -1) {
//System.out.println(c1);
c.update(c1);
}
file.close();
long e = System.currentTimeMillis();
System.out.println("耗时:"+(e-s)+"ms");
return c.getValue();
}
public static long checkSumRandomAccess(String fileName) throws IOException{
long s = System.currentTimeMillis();
RandomAccessFile ra = new RandomAccessFile("src\\chapter1\\t2.txt", "r");
int len = (int) ra.length();
System.out.println(len);
//CRC32 校验文件,查看破损等等
CRC32 c = new CRC32();
for (int i = 0; i < len; i++) {
ra.seek(i);
c.update(ra.readByte());
}
ra.close();
long e = System.currentTimeMillis();
System.out.println("耗时:"+(e-s)+"ms");
return c.getValue();
}
}

 

 posted on 2017-03-13 11:44  ffewi  阅读(77)  评论(0)    收藏  举报