NIO系列一:基本概念

NIO在jdk1.4被引入,弥补了IO的不足,在标准java代码中提供了高速且面向块的IO。

相比以前IO而言:两者最重要的区别就是在数据打包和传输方式上有不同,IO以流的方式传输数据,NIO以块的方式传输数据

面向流的I/O系统一次一个字节地处理数据。一个输入流产生一个字节的数据,一个输出流消费一个字节的数据。为流式数据创建过滤器非常容易。链接几个过滤器,以便每个过滤器只负责单个复杂处理机制的一部分,这样也是相对简单的。不利的一面是,面向流的I/O通常相当慢。
NIO与原来的I/O有同样的作用和目的,但是它使用块I/O的处理方式。每一个操作都在一步中产生或者消费一个数据块。按块处理数据比按(流式的)字节处理数据要快得多。但是面向块的I/O缺少一些面向流的I/O所具有的优雅性和简单性。

通道和缓冲区

在NIO中所有的数据都是利用缓冲区(Buffer)进行处理的,缓冲区是一个容器对象,它包含一些要写入或者读取的数据,在IO中,可以将数据写入或者读取的stream对象中。

缓冲区实际上为一个数组,通常为一个字节数组。而且它也提供了对数据结构化的访问,并且跟踪系统的读写进程。

举例来说:ByteBuffer,ByterBuffer是一个最常用的缓冲区,可以利用get/put对底层字节数组进行获取和设置。

public abstract class ByteBuffer
    extends Buffer
    implements Comparable<ByteBuffer>
{

    final byte[] hb;                  // Non-null only for heap buffers
    final int offset;
    boolean isReadOnly;                 // Valid only for heap buffers
设置put,重载了多个put方法,取一种

 public ByteBuffer put(byte[] src, int offset, int length) {
        checkBounds(offset, length, src.length);
        if (length > remaining())
            throw new BufferOverflowException();
        int end = offset + length;
        for (int i = offset; i < end; i++)
            this.put(src[i]);
        return this;
    }
获取ByteBuffer间的元素

 public ByteBuffer get(byte[] dst, int offset, int length) {
        checkBounds(offset, length, dst.length);
        if (length > remaining())
            throw new BufferUnderflowException();
        int end = offset + length;
        for (int i = offset; i < end; i++)
            dst[i] = get();
        return this;
    }

例:

/**
 * ByteBuffer测试
 */
public static void testFloatBuffer() throws Exception {
	// 分配一个容量为10的float缓冲区
	ByteBuffer buffer = ByteBuffer.allocate(10);
	for (int i = 0; i < buffer.capacity(); i++) {
		buffer.put((byte)(i));
	}
	// 反转缓冲区
	buffer.flip();
	// 告知在当前位置和限制之间是否存在元素
	while (buffer.hasRemaining()) {
		System.out.println(buffer.get());
	}
}

通道Channel是对原IO包中流的模拟,可以通过它读取或者写入数据。通道相对于流而言,通道是双向的,通道可以用于读、写或者同时进行读写,而流只是在一个方向上流动。

NIO中数据的读/写:

读:创建一个缓冲区,然后利用通道将数据读取到该缓冲区中即可。

/**
 * 读取一个文件的前1024个字符
 */
public static void getFileContent(File file) throws Exception {
	FileInputStream fis=new FileInputStream(file);
	FileChannel cin=fis.getChannel();
	//创建一个容量为1024的字节缓冲区
	ByteBuffer buffer=ByteBuffer.allocate(1024);
	//利用通道将数据写入到缓冲区
	cin.read(buffer);
	System.out.println(new String(buffer.array()));
	cin.close();
	fis.close();
}

写:创建一个缓冲区,然后填充数据,后利用通道用该数据进行写入操作。

/**
 * 写入文件
 */
public static void writeFileContent(String filePath) throws Exception {
	File file = new File(filePath);
	FileOutputStream fos = null;
	FileChannel cout = null;
	if (!file.exists()) {
		file.createNewFile();
	}
	//通过FileOutputStream获取缓冲区
	fos = new FileOutputStream(file);
	cout = fos.getChannel();
	//创建一个byte缓冲区
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	//往byte缓冲区中存入数据
	for (int i = 0; i < 9; i++) {
		buffer.put((byte)(i+'A'));
	}
	//反转缓冲区,必须写,如果没有,则是从文件最后开始读取的,通过这个能将buffer当前位置position更改为
	//buffer缓冲区的第一个,这样才能对buffer进行遍历读取
	buffer.flip();
	//利用FileChannel执行写入操作
	cout.write(buffer);
	cout.close();
	fos.close();
}

文件的拷贝:

/**
 * 文件的拷贝
 */
public static void copyFile(File source, File target) throws Exception {
	FileInputStream fis = new FileInputStream(source);
	FileOutputStream fos = new FileOutputStream(target);
	FileChannel cin = fis.getChannel();
	FileChannel cout = fos.getChannel();
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	int temp = 0;
	while ((temp = cin.read(buffer)) != -1) {
		buffer.flip();
		cout.write(buffer);
		// 重置buffer
		buffer.clear();
	}
	closeResource(fis,fos,cin,cout);
}

/**
 * 关闭流和通道
 */
public static void closeResource(FileInputStream fis, FileOutputStream fos,
		FileChannel cin, FileChannel cout) throws Exception {
	if (cin != null) {
		cin.close();
	}
	if (cout != null) {
		cout.close();
	}
	if (fis != null) {
		fis.close();
	}
	if (fos != null) {
		fos.close();
	}
}
















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值