java-nio

来源:互联网 发布:ubuntu 卸载anaconda 编辑:程序博客网 时间:2024/05/17 04:22
//新IO,他们位于java.nio包中,合称新IO
//对以下特性加以支持
//1.字符集编码器和解码器
//2.非阻塞的I/O
//3.内存映射文件
//4.文件加锁机制

/**
内存映射文件:
1.大多数操作系统都可以利用虚拟内存实现来将一个文件或者文件的一部分
"映射"到内存中,然后,这个文件就可以当作是内存数组一
访问,这比传统的文件操作要快得多
java.nio包使得内存映射很简单:步骤
1.从文件中获得哦一个通道(channel),通道时用于磁盘文件的一种抽象
我们可以通过调用getChannel()方法来获得通道,这个方法已经添加到
FileInputStream类中,FileOutputStream和RandomAccessFile类
FileInputStream in=new FileInputStream(...);
FileChannel channel=in.getChannel();
2.通过调用FileChannel类的map方法从这个通道中获得已ge
MappedByteBuffer,可以有三种模式:
2.1 FileChannel.MapMode.READ_ONLY:所产生的缓冲区是只读的,任何对该
缓冲区的写入的尝试都会导致
ReadOnlyBufferException异常
2.2 FileChannel.MapMode.READ_WRITE:所产生的缓冲区是可写的,任何修改都会在某个时刻写回到文件中
注意:其他映射同一个文件的程序可能不能立即看到这些修改
2.3 FileChannel.MapMode.PRIVATE:所产生的缓冲区是可写的,但是任何修改对这个缓冲区来说是私有的,不会传播到文件中
3.缓冲区支持顺序和随机数据访问,他有一个可能通过get和put操作来推动的位置
while(buffer.hasRemaining()){
byte b=buffer.get();
}

*/


public class NIOTest{

public static long checksumInputStream(String fileName){ throws IOException{

InputStream in=new InputStream(fileName);
CRC32 crc=new CRC32();
int c;
while((c=in.read())!=-1){
crc.update();
return crc.getValue();
}
}
public static long checksumBufferedInputStream(String name) throws IOException{
InnputStream in=new BufferedInputStream(new FileInputStream(fileName));
CRC32 crc=new CRC32();
int c;
while((c=in.read())!=-1){
crc.update();
return crc.getValue();
}
}
public static long checksumRandomAccessFile(String filename) throws IOException{
RandomAccessFile file=new RandomAccessFile(filename,"r");
long lengt=file.length();
CRC32 crc=new CRC32();
for(long p=0;p<length;p++){
file.seek(p);
int c=file.readByte();
crc.update();
}
return crc.getValue();
}
public static long checksumMappingnFile(String filename) throws IOExcption{
FileInputStream in=new FileInputStream(filename);
FileChannel channel=in.getChannel();
CRC32 cec=new CRC32();
int length=(int)channel.size();
MappedByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY,0,length);
for(int p=0;p<length;p++){
int c=buffer.get(p);
crc.update();
}
return crc.update();
}
}
0 0
原创粉丝点击