面试知识点--NIO

大部分内容取自thinking in java。。宝典级的书

  1. package nio;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.RandomAccessFile;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.FileChannel;
  7. /**
  8.  * NIO速度的提高,是由于使用了更接近于操作系统I/O处理方式的结构:channels和buffers.
  9.  * 如果将channel比喻成墙角,那么buffer就是一把锄头。
  10.  * 我们不会直接搬墙角。但是,只要锄头挥得好......
  11.  * 
  12.  * 直接和channel打交道的只有一种最低层实现的类型:ByteBuffer
  13.  * 创建的时候甚至需要指定分配多少内存空间,它仅实现了byte格式及基本数据格式(primitive data)
  14.  * 的输入输出函数,甚至不可以直接输入一个Object或者String。
  15.  * 
  16.  * channel的作用非常简单:处理ByteBuffer的读写,锁定文件块内容
  17.  * channel的构造方法来自于对原I/O系统中3个基于byte流的对象的修改:
  18.  * FileInputStream,FileOutputStream,RandomAccessFile
  19.  * 
  20.  * @author wei.songw
  21.  * Oct 16, 2008 3:54:16 PM
  22.  */
  23. public class Basic {
  24.     private static final int BSIZE = 1024;
  25.     
  26.     public static void main(String[] args) throws Exception{
  27.         
  28.         //write file
  29.         FileChannel fc = new FileOutputStream("abc.txt").getChannel();
  30.         fc.write(ByteBuffer.wrap("some string".getBytes()));
  31.         fc.close();
  32.         
  33.         fc = new RandomAccessFile("abc.txt","rw").getChannel();
  34.         fc.position(fc.size()); //go the end
  35.         fc.write(ByteBuffer.wrap("more string".getBytes()));
  36.         fc.close();
  37.         
  38.         fc = new FileInputStream("abc.txt").getChannel();
  39.         ByteBuffer bf = ByteBuffer.allocate(BSIZE);
  40.         fc.read(bf);
  41.         bf.flip(); //Notice here.flip filter!!
  42.         while(bf.hasRemaining()) {
  43.             System.out.print((char)bf.get());
  44.         }
  45.     }
  46. }
  1. package nio;
  2. import java.nio.ByteBuffer;
  3. import java.nio.IntBuffer;
  4. /**
  5.  * ByteBuffer虽然仅持有byte数组,但是API提供了一些方法处理primitives
  6.  * (给对象提供相应的配套操作,往往是一个好的OO设计理念。
  7.  *  比如提供Collection,就得配套提供的Iterator遍历器,而不要让用户自己
  8.  *  去实现迭代或者是依赖异常判断是否越界)
  9.  *  
  10.  *  (为API提供一致性的结构和函数命名规范也是一种好习惯。。asCharBuffer,
  11.  *      asIntBuffer , asDoubleBuffer , getInt, getLong ....)
  12.  * @author wei.songw
  13.  * Oct 16, 2008 8:19:49 PM
  14.  */
  15. public class GetData {
  16.     private static final int BSIZE = 1024;
  17.     
  18.     public static void main(String[] args) throws Exception{
  19.         ByteBuffer bb = ByteBuffer.allocate(BSIZE); //filled by 0
  20.         
  21.         //char
  22.         bb.asCharBuffer().put("heihei");
  23.         char c;
  24.         while((c = bb.getChar()) != 0) {
  25.             System.out.print(c+" ");
  26.         }
  27.         
  28.         bb.rewind();
  29.         //int
  30.         bb.asIntBuffer().put(12345);
  31.         System.out.print(bb.getInt());
  32.         
  33.         //batches
  34.         bb.clear();
  35.         IntBuffer ib = bb.asIntBuffer();
  36.         ib.put(new int[]{11,22,33,44,55});
  37.         System.out.println(ib.get(3));
  38.     }   
  39. }
  1. package nio;
  2. import java.io.RandomAccessFile;
  3. import java.nio.MappedByteBuffer;
  4. import java.nio.channels.FileChannel;
  5. /**
  6.  * 网上copy的例子,内存映射文件主要是来操作大文件.最大可达2GB. 
  7.  * @author wei.songw
  8.  * Oct 16, 2008 10:34:52 PM
  9.  */
  10. public class MemoryMappedFile {
  11.        static int length = 0x8FFFFFF// 128 Mb 
  12.        public static void main(String[] args) throws Exception { 
  13.          MappedByteBuffer out =  
  14.            new RandomAccessFile("test.dat""rw").getChannel() 
  15.            .map(FileChannel.MapMode.READ_WRITE, 0, length); 
  16.          for(int i = 0; i < length; i++) 
  17.            out.put((byte)'x'); 
  18.          System.out.println("Finished writing"); 
  19.          for(int i = length/2; i < length/2 + 6; i++) 
  20.            System.out.print((char)out.get(i));    //read file 
  21.        } 
  22. }
  1. package nio;
  2. import java.io.FileOutputStream;
  3. import java.nio.channels.FileLock;
  4. import java.util.concurrent.TimeUnit;
  5. /**
  6.  * 主要是研究tryLock(),Lock()的API.
  7.  * 无参的全文锁定支持文件大小的改变,
  8.  * 而固定大小的部分锁定则不会自动适应文件的增长(
  9.  * if a locked region initially contains the end of the file
  10.  *  and the file grows beyond the region then the new portion of the file
  11.  *   will not be covered by the lock.)
  12.  * 
  13.  * 
  14.  * 文件锁同样支持MemoryMappedFile
  15.  * 
  16.  * @author wei.songw
  17.  * Oct 16, 2008 11:16:14 PM
  18.  */
  19. public class FileLocking {
  20.     public static void main(String[] args) throws Exception {
  21.         FileOutputStream fos = new FileOutputStream("abc.txt");
  22.         //locking the hole file
  23.         FileLock fl = fos.getChannel().tryLock();
  24.         if(fl != null) {
  25.             System.out.println("file locked");
  26.             //do your work
  27.             TimeUnit.MILLISECONDS.sleep(2000);      
  28.             fl.release();
  29.             System.out.println("Released lock");
  30.         }
  31.         
  32.         //for locking a part of the file,use:
  33.         //FileLock tryLock(long position, long size, boolean shared)
  34.         //FileLock Lock(long position, long size, boolean shared)
  35.         
  36.         
  37.         fos.close();
  38.     }
  39. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值