ByteBuffer buf = ByteBuffer.allocate(256);
byte[] input = new byte[15];
System.in.read(input);
buf.put(input);
// 调用flip()使limit变为当前的position的值,position变为0,
// 为接下来从ByteBuffer读取做准备
buf.flip();
byte[] content = new byte[buf.limit()];
buf.get(content);
System.out.print(new String(content));
// 调用clear()使position变为0,limit变为capacity的值,
// 为接下来写入数据到ByteBuffer中做准备
buf.clear();
CRC32 crc = new CRC32();
InputStream in = new FileInputStream(fileName);
//InputStream in = new BufferedInputStream(new FileInputStream(fileName));
//RandomAccessFile in= new RandomAccessFile(fileName,"r");
try {
int c;
while((c=in.read())!=-1){
crc.update(c);
}
}catch(IOException e){
e.printStackTrace();
}
return crc.getValue();
FileInputStream in = new FileInputStream(fileName);
FileChannel channel = in.getChannel();
int length = (int) channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
buffer.load();//调用load()ByteBuffer才不为空
byte[] byte1=new byte[buffer.limit()];
buffer.get(byte1);
crc.update(byte1);
FileInputStream :耗时312ms
BufferedInputStream:耗时16ms
RandomAccessFile:耗时312ms
Mapped-FileInputStream:耗时16ms或0ms