您的位置:首页 > 理论基础 > 计算机网络

Java网络编程(新IO概述)

2015-08-28 18:40 459 查看

新IO概述

新I0采用内存映射文件的方式来处理输入/输出,新I0将文件或文件的一段区域映射

到内存中,这样就可以像访问内存一样来访问文件了(这种方式模拟了操作系统上的虚拟内存的概念),

通过这种方式来进行输入/输出比传统的输入/输出要快得多。

中NIO相关的包如下:

java.nio包:主要提供了一些和Buffer相关的类。

java.nio.channels包:主要包括Channel和Selector相关的类。

java.nio.charset包:主要包含和字符集相关的类。

java.nio.channels.spi包:主要包含提供Channel服务的类。

java.nio.charset.spi包:主要包含提供字符集服务的相关类。

在新IO系统中所有数据都需要通过Channel通道传输;

Channel与传统的InputStream, OutputStream最大的区别在于它提供了一个map方法,通过该map方法可以直接将“一块数据”映射到内存中。如果说传统的输入/输出系统是面向流的处理,而新10则是面向块的处理。

Buffer可以被理解成一个容器,它的本质是一个数组,发送到放到Buffer中,而从Channel中读取的数据也必须先读到Buffer中

除了Channel和Buffer之外,新10还提供了用于将UNICODE字符串映射成字节序列以及逆映射操作的Charset类,还提供了用于支持非阻塞式输入输出的Selector类。

Buffer使用

Class test{

Public static void main(String[] args)

{

CharBuffer buff = CharBuffer.allocate(8);

System.out.println(buff.capacity()+buff.limit()+buff.position());

buff.put(‘a’);

buff.put(‘b’);

System.out.println(buff..position());//每加一个元素position向后移一位

buff.flip();//准备取

System.out.println(buff..limit());//limit移到原position位置position=1

System.out.println(buff..get());

buff.clear();//清空position=1 limit=capacity

}


 

Chnnel使用

Channel类似于传统的流对象,但与传统的流不同的是,Channel有两个主要的区别:

Channel可以直接将指定文件的部分或全部直接映射成Buffer.

程序不能直接访问Channel中的数据,包括读取、写入都不行,Channe!只能与Buffer进行

交互。也就是说,如果要从Channel中取得数据,必须先用Buffer从Channel中取出一些

数据,然后让程序从Buffer中取出这些数据;如果要将程序中的数据写入Channel,一样先

让程序将数据放入Buffer中,程序再将buffer里的输入写入Channel中。

public static void main(String[] args)
{
FileChannel inChannel = null;
FileChannel outChannel = null;
try
{
File f = new File("FileChannelTest.java");
inChannel = new FileInputStream(f).getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY,0,f.length());
Charset charset = Charset.forName("GBK");
outChannel = new FileOutputStream("a.txt").getChannel();
outChannel.write(buffer);
buffer.clear();
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer= decoder.decode(buffer);
System.out.println(charBuffer);
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if(inChannel !-null)
innChanel.close();
if(outChannel !=null)
outChannel.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}

}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java nio