zl程序教程

您现在的位置是:首页 >  后端

当前栏目

了解一下JAVA中的NIO模块

JAVAnio模块 了解 一下
2023-09-14 08:59:37 时间
复制代码
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();

}
复制代码