TCP-IP学习笔记二:NIO的网络编程Buffer简单使用

TCP/IP学习笔记二:NIO的网络编程Buffer简单使用

标签(空格分隔):网络编程 NIO Buffer


NIO的有三种模型:ByteBuffer (position/limit/capacity) / Channel / Selector 通道选择器
先介绍前两种的简单示例,NIO的Buffer的简单使用、文件的读写和文件的复制
如下实例中其实也是阻塞I/O(并非真正的NIO)。对于真正的非阻塞I/O实例在下篇文章中展示。

NIO的Buffer的使用:

package com.nio.buffer;

import java.nio.ByteBuffer;
/**
 * ByteBuffer实例
 * @author MOTUI
 *
 */
public class TestBuffer {

    public static void main(String[] args) {
        //创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate(5);

        System.out.println("初始化状态:"+buffer.position()+","+buffer.limit()+","+buffer.capacity());

        //写入两个字节
        buffer.put((byte)'a');
        buffer.put((byte)'b');

        System.out.println("存入两个字节状态:"+buffer.position()+","+buffer.limit()+","+buffer.capacity());

        buffer.flip();

        System.out.println("重置状态:"+buffer.position()+","+buffer.limit()+","+buffer.capacity());

        System.out.println("打印两个字节:");
        //读取写入的字节
        while(buffer.hasRemaining()){
            System.out.print(buffer.get()+" ");
        }

        //换行
        System.out.println();

        //重置
        buffer.clear();

        //存入一个字节
        buffer.put((byte)'c');

        //buffer.flip();
        System.out.println("打印未重置:");
        //读取
        while(buffer.hasRemaining()){
            System.out.print(buffer.get()+" ");
        }
        //换行
        System.out.println();

        //设置参数
        buffer.position(0);
        buffer.limit(1);

        System.out.println("打印重置后:");
        //读取写入的新字节
        while(buffer.hasRemaining()){
            System.out.print(buffer.get()+" ");
        }

    }

}

运行结果为:

初始化状态:0,5,5
存入两个字节状态:2,5,5
重置状态:0,2,5
打印两个字节:
97 98 
打印未重置:
98 0 0 0 
打印重置后:
99 

对于Buffer的图解:
TCP-IP学习笔记二:NIO的网络编程Buffer简单使用_第1张图片

文件的写操作:

package com.nio.buffer;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
 * 文件写入
 * @author MOTUI
 *
 */
public class TestWriteFile {

    public static void main(String[] args) throws Exception {
        //输出流
        FileOutputStream fos = new FileOutputStream("write.txt");
        //获得管道
        FileChannel writeChannel = fos.getChannel();
        //创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        String byteStr = "你好,他好,大家好!";
        //写入数据
        buffer.put(byteStr.getBytes());
        buffer.flip();
        //通过管道写入数据
        writeChannel.write(buffer);
        //关闭流
        if (writeChannel.isOpen()) writeChannel.close();
        fos.close();
    }

}

文件的读操作:

package com.nio.buffer;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
 * 文件读取
 * @author MOTUI
 *
 */
public class TestRead {
    public static void main(String[] args) throws Exception {
        //输入流
        FileInputStream fis = new FileInputStream("write.txt");
        //获得管道
        FileChannel readChanner = fis.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //存储读取的字节
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        while (true) {
            //重置buffer
            buffer.clear();
            //读取数据
            len = readChanner.read(buffer);

            buffer.flip();

            //判断是否读到末尾
            if (len == -1) break;
            while (buffer.hasRemaining()) {
                //写入数据
                baos.write(buffer.get());
            }
        }
        //关闭流
        if (readChanner.isOpen()) readChanner.close();
        fis.close();
        //打印
        System.out.println(baos.toString());

    }
}

运行结果:

你好,他好,大家好!

文件的拷贝:

package com.nio.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
 * 文件拷贝
 * @author MOTUI
 *
 */
public class TestCopy {
    public static void main(String[] args) throws Exception {
        //读入文件流
        FileInputStream fis = new FileInputStream("ssss.png");
        //写入文件流
        FileOutputStream fos = new FileOutputStream("aaaa.png");
        //获得读管道
        FileChannel readChannel = fis.getChannel();
        //获取写管道
        FileChannel writeChannel = fos.getChannel();
        //创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        int len = 0;

        while (true) {
            //清除Buffer
            buffer.clear();
            //读数据
            len = readChannel.read(buffer);
            //判断是否读到末尾
            if(len == -1) break;
            buffer.flip();
            //写入数据
            if (buffer.hasRemaining()) {
                writeChannel.write(buffer);
            }
        }
        //关闭流
        if(writeChannel.isOpen()) writeChannel.close();
        if(readChannel.isOpen()) readChannel.close();
        fis.close();
        fos.close();
    }
}

总结:

    对于NIO的Buffer的操作较简单,掌握基本使用即可。

你可能感兴趣的:(TCP-IP,网络编程,buffer,nio)