了解一下JAVA中的NIO模块

  1. 云栖社区>
  2. 博客>
  3. 正文

了解一下JAVA中的NIO模块

天飞 2016-05-16 15:02:28 浏览642
展开阅读全文

网上资料大把,但要写写代码,我这个年纪的人才有一点点记忆了。。

参考URL:

http://blog.csdn.net/wuxianglong/article/details/6612282

复制代码
package com.cg.io;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class TestIntBuffer {
  static private final byte message[] = {83, 111, 109, 101, 32, 98, 98};
  static private String fileName = "d:\\hehehe\\test.txt";
  public static void main(String[] args) throws Exception {
    FileOutputStream fout = new FileOutputStream(fileName);
    FileChannel fc = fout.getChannel();
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    output("初始化", byteBuffer);
    for (int i=0; i<message.length; ++i) {
      byteBuffer.put(message[i]);
    }
    byteBuffer.flip();
    output("调用flip()", byteBuffer);
    fc.write(byteBuffer);
    output("调用write()", byteBuffer);
    fout.close();
    byteBuffer.clear();
    output("调用clear()", byteBuffer);

    FileInputStream fin = new FileInputStream(fileName);
    fc = fin.getChannel();
    fc.read(byteBuffer);
    output("调用read()", byteBuffer);
    byteBuffer.flip();
    output("调用flip()", byteBuffer);
    while (byteBuffer.remaining() > 0) {
      byte b = byteBuffer.get();
      System.out.print(((char)b));
    }
    output("调用getChannel()", byteBuffer);
    byteBuffer.clear();
    output("调用clear()", byteBuffer);
    fin.close();

    IntBuffer intBuffer = IntBuffer.allocate(8);

    for (int i=0; i < intBuffer.capacity(); ++i) {
      int j = 2 * (i + 1);
      intBuffer.put(j);
    }
    intBuffer.flip();

    while (intBuffer.hasRemaining()) {
      int j = intBuffer.get();
      System.out.print(j + " ");
    }
  }
  public static void output(String step, Buffer buffer){
    System.out.println(step + " : ");
    System.out.println("capacity: " + buffer.capacity() + ", ");
    System.out.println("position: " + buffer.position() + ", ");
    System.out.println("limit: " + buffer.limit() + ", ");
    System.out.println();

  }
}
复制代码

网友评论

登录后评论
0/500
评论
天飞
+ 关注