码迷,mamicode.com
首页 > 编程语言 > 详细

了解一下JAVA中的NIO模块

时间:2016-05-09 18:38:08      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

参考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();

  }
}

技术分享

了解一下JAVA中的NIO模块

标签:

原文地址:http://www.cnblogs.com/aguncn/p/5474773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!