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