java nio

Java NIO非堵塞应用通常适用用在I/O读写等方面,我们知道,系统运行的性能瓶颈通常在I/O读写,包括对端口和文件的操作上,过去,在打开一个I/O通道后,read()将一直等待在端口一边读取字节内容,如果没有内容进来,read()也是傻傻的等,这会影响我们程序继续做其他事情,那么改进做法就是开设线程,让线程去等待,但是这样做也是相当耗费资源的。

Java NIO非堵塞技术实际是采取Reactor模式,或者说是Observer模式为我们监察I/O端口,如果有内容进来,会自动通知我们。

package com.java.xiong.file15;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class FileChanelTest {
	private static FileInputStream fileInputStream;
	private static FileOutputStream fileOutputStream;

	public static void main(String[] args) {

		File files = new File("src/com/java/xiong/file15/FileChanelTest.java");
		File filess = new File("1.txt");
		try {

			fileInputStream = new FileInputStream(files);
			FileChannel filein = fileInputStream.getChannel();
			fileOutputStream = new FileOutputStream(filess);
			FileChannel fileout = fileOutputStream.getChannel();
			MappedByteBuffer mapin = filein.map(FileChannel.MapMode.READ_ONLY,
					0, files.length());
			// 使用GBK来创建解码
			Charset cset = Charset.forName("GBK");
			fileout.write(mapin);
			// 将Buffer 界限和位置复原
			mapin.clear();
			// 创建解码对象
			CharsetDecoder chard = cset.newDecoder();
			// byteBuffer转换成charBuffer
			CharBuffer charc = chard.decode(mapin);
			System.out.println(charc.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


你可能感兴趣的:(java,nio,buffer)