NIO案例以及部分概念

java NIO NIO提供了一个全新底层i/o模型。与最初的java.io面向流的概念不同,NIO采用了面向 块的概念。这意味着尽在可能,i/o操作以大的数据块为单位进行,而不是一个一个字节 或字符进行操作,采用这种方式,java i/o性能有了很大的提高。 新i/o没有在原来的io基础山操作,而是采用了全新的接口 新特性 多路选择的非封锁io设施 支持文件锁集和内存映射 支持正则表达式的模式匹配设施 支持字符集编码和译码器 缓存区与buffer nio中所有操作都要使用到缓存区处理,且所有的读写操作都是通过缓存区完成的,缓存区 是一个线性的、有序的数据集,只能容纳某种特定的数据类型
public static void main(String[] args) {
//IntBuffer buff =IntBuffer.allocate(10); //开辟空间
//创建直接缓冲区,利用系统io
ByteBuffer buff = ByteBuffer.allocateDirect(10);
System.out.println("写入数据前的 position,limit和capacity"); System.out.println(""+buff.position()+"======="+buff.limit()+"======="+buff.capacity()); // int []temp ={6,8,10}; byte [] temp={6,8,10}; // buff.put(3); //向缓存区写入数据 buff.put(temp); System.out.println("写入数据之后的缓存区变量"); System.out.println(buff.position()+"====="+buff.limit()+"======"+buff.capacity()); buff.flip(); //翻转 System.out.println("翻转"); System.out.println(buff.position()+"======="+buff.limit()+"====="+buff.capacity()); while (buff.hasRemaining()) { int x =buff.get(); System.out.println(x+"-"); } } 深入缓存区操作 position:表示下一个缓存区读取或者写入的操作指针 limit: 表示有多少数据需要读取 capacity:表示缓存区最大的容量 limit<=limit slice()方法从一个缓存区中创建一个新的子缓冲区,子缓存区与原缓冲区中的部分 数据可以共享。 通道 通道用来读取和写入数据,通道类似于之前的输入/输出流,但是程序不会直接操作通道,所有的 内容都是先写入或者读写到缓冲区,再通过缓存区取得或者写入的。 方法可以看api public class TestChannel {
public static void main(String[] args) throws IOException { String []info= {"java","android","python","c"}; File file =new File("d:"+File.separator+"out.txt"); FileOutputStream output=new FileOutputStream(file); FileChannel channel =output.getChannel(); ByteBuffer buff=ByteBuffer.allocate(1024); for (int i = 0; i < info.length; i++) { buff.put(info[i].getBytes()); } buff.flip(); channel.write(buff); channel.close(); output.close(); } } 内存映射 可以把文件映射到内存中,这样文件内的数据就可以用内存读写指令来访问。 public class FileChannelTest { public static void main(String[] args) throws IOException { File file = new File("d:"+File.separator+"out.txt"); FileInputStream in= new FileInputStream(file); FileChannel channel =in.getChannel(); MappedByteBuffer buff =channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); //声明内存映射 byte b[] =new byte[(int) file.length()]; int foot=0; while (buff.hasRemaining()) { b[foot++]=buff.get(); } System.out.println(new String(b)); channel.close(); in.close(); } } 文件锁 【NIO案例以及部分概念】当一个线程将文件锁定后,其他线程是无法读取此文件的。
public class FileLockTest {
public static void main(String[] args) throws IOException, InterruptedException { File file = new File("d:"+File.separator+"out.txt"); FileOutputStream out = new FileOutputStream(file,true); FileChannel channel =out.getChannel(); FileLock lock =channel.tryLock(); if(lock!=null){ System.out.println("this file is lock "); Thread.sleep(3000); lock.release(); System.out.println("this file is unlock "); } channel.close(); out.close(); } } 字符集

    推荐阅读