IO | NIO |
---|---|
面向流(Stream Oriented) | 面向缓冲区(Buffer Oriented) |
阻塞IO(Blocking IO) | 非阻塞IO(Non Blocking IO) |
无 | 选择器(Selectors) |
一、根据数据类型的不同,提供了相应类型的缓冲区(Boolean 除外)
ByteBuffer
CharBuffer
IntBuffer
LongBuffer
ShortBuffer
FloatBuffer
DoubleBuffer
上述缓冲区的管理方式几乎一致,通过 allocate() 获取缓冲区
二、缓冲区存取数据的两个核心方法
三、缓冲区的四个核心属性
四、直接缓冲区,非直接缓冲区
五、代码实践
void contextLoads() {
// 分配指定大小的缓冲区
System.out.println("============== allocate ================");
ByteBuffer buffer = ByteBuffer.allocate(1024);
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 1024
// 添加数据
System.out.println("============== put ================");
String str = "brave";
buffer.put(str.getBytes());
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 5
System.out.println(buffer.limit()); // 1024
// 切换到读数据模式
System.out.println("============== flip ================");
buffer.flip();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 5
// 读取数据
System.out.println("============== get ================");
byte[] bst = new byte[buffer.limit()];
buffer.get(bst);
System.out.println(new String(bst)); // brave
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 5
System.out.println(buffer.limit()); // 5
// 可重复读
System.out.println("============== rewind ================");
buffer.rewind();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 5
// 清空缓冲区(数据依然存在)
System.out.println("============== clear ================");
buffer.clear();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 0
System.out.println(buffer.limit()); // 1024
System.out.println((char)buffer.get()); // b
}
void bufTest(){
System.out.println("========= mark =========");
ByteBuffer buffer = ByteBuffer.allocate(1024);
String str = "brave";
buffer.put(str.getBytes());
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 5
System.out.println(buffer.limit()); // 1024
buffer.flip();
byte[] bst = new byte[buffer.limit()];
buffer.get(bst,0,2);
System.out.println(new String(bst,0,2)); // br
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 2
System.out.println(buffer.limit()); // 5
// 标记 position = 2
buffer.mark();
buffer.get(bst,2,2);
System.out.println(new String(bst,2,2)); // av
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 4
System.out.println(buffer.limit()); // 5
// 返回到标记点 position = 2
buffer.reset();
System.out.println(buffer.capacity()); // 1024
System.out.println(buffer.position()); // 2
System.out.println(buffer.limit()); // 5
// 缓冲区中是否还有数据
if(buffer.hasRemaining()){
// 返回缓冲区中剩余的数据个数
System.out.println(buffer.remaining()); // 3
}
}
一、通道的主要实现类
二、获取通道
三、通道之间的数据传输
四、分散(Scatter)与聚集(Gather)
五、字符集:CharSet
@Test
void channelTest() throws Exception{
FileInputStream fis = new FileInputStream("1.jpg");
FileOutputStream fos = new FileOutputStream("2.jpg");
// 获取通道
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 将通道中的数据存入缓冲区
while(inChannel.read(buf) != -1){
// 切换到读数据模式
buf.flip();
// 将缓冲区中的数据写入通道
outChannel.write(buf);
// 清空通道
buf.clear();
}
outChannel.close();
inChannel.close();
fos.close();
fis.close();
}
@Test
void channelTest() throws Exception{
FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
// 内存映射文件
MappedByteBuffer inMappedByteBuffer = inChannel.map(MapMode.READ_ONLY,0, inChannel.size());
MappedByteBuffer outMappedByteBuffer = outChannel.map(MapMode.READ_WRITE,0, inChannel.size());
// 直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMappedByteBuffer.limit()];
inMappedByteBuffer.get(dst);
outMappedByteBuffer.put(dst);
outChannel.close();
inChannel.close();
}
@Test
void channelTest() throws Exception{
FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("5.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
// inChannel.transferTo(0, inChannel.size(),outChannel);
outChannel.transferFrom(inChannel, 0, inChannel.size());
outChannel.close();
inChannel.close();
}
@Test
void channelTest() throws Exception{
RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
// 获取通道
FileChannel channel = raf1.getChannel();
// 分配指定大小的缓冲区
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
// 分散读取
ByteBuffer[] bufs = {buf1, buf2};
channel.read(bufs);
for(ByteBuffer byteBuffer : bufs){
byteBuffer.flip();
}
System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
System.out.println("---------------------");
System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
// 聚集写入
RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
FileChannel channel2 = raf2.getChannel();
channel2.write(bufs);
raf1.close();
raf2.close();
}
// 查看所有支持的编码
void charset() throws Exception{
Map<String,Charset> map = Charset.availableCharsets();
Set<Entry<String,Charset>> set = map.entrySet();
for(Entry<String,Charset> entry:set){
System.out.println(entry.getKey()+"="+entry.getValue());
}
}
// 编码器,解码器
void charsetTest() throws Exception{
Charset cs1 = Charset.forName("GBK");
// 获取编码器
CharsetEncoder ce = cs1.newEncoder();
// 获取解码器
CharsetDecoder cd = cs1.newDecoder();
CharBuffer cBuf = CharBuffer.allocate(1024);
String str = "心有猛虎细嗅蔷薇";
cBuf.put(str);
cBuf.flip();
// 编码
ByteBuffer bBuf = ce.encode(cBuf);
for(int i= 0;i < str.length() * 2;i++){
System.out.println(bBuf.get());
}
// 解码
bBuf.flip();
CharBuffer cBuf2 = cd.decode(bBuf);
System.out.println(cBuf2.toString());
}
一、通道(Channel) :负责连接
二、缓冲区(Buffer) :负责数据的存取
三、迭择器(Selector) :
四、代码实践
public class Aserver {
public static void main(String[] args) throws Exception{
// 获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(Paths.get("3.txt"),StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);
// 绑定连接
ssChannel.bind(new InetSocketAddress(9898));
// 获取客户端链接的通道
SocketChannel sChannel = ssChannel.accept();
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 接收客户端的数据,保存到本地
while(sChannel.read(buf) != -1){
buf.flip();
outChannel.write(buf);
buf.clear();
}
// 发送反馈给客户端
buf.put("服务端接收数据成功".getBytes());
buf.flip();
sChannel.write(buf);
// 关闭通道
sChannel.close();
outChannel.close();
ssChannel.close();
}
}
public class Aclient {
public static void main(String[] args) throws Exception{
// 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
FileChannel inChannel = FileChannel.open(Paths.get("1.txt"), StandardOpenOption.READ);
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 读取本地文件,发送到服务器
while(inChannel.read(buf) != -1){
buf.flip();
sChannel.write(buf);
buf.clear();
}
sChannel.shutdownOutput();
// 接收服务端反馈
int len = 0;
while((len = sChannel.read(buf)) != -1){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
// 关闭通道
inChannel.close();
sChannel.close();
}
}
public class Aserver {
public static void main(String[] args) throws Exception{
// 获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
// 切换成非阻塞模式
ssChannel.configureBlocking(false);
// 绑定连接
ssChannel.bind(new InetSocketAddress(9898));
// 获取选择器
Selector selector = Selector.open();
// 将通道注册到选择器,指定监听事件
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
// 轮询式的获取选择器上已经准备就绪的事件
while(selector.select() >0 ){
// 获取当前选择器中所有注册的"选择键(已就绪的监听事件)"
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
// 获取准备就绪的事件
SelectionKey sk = it.next();
// 判断具体是什么事件准备就绪
if(sk.isAcceptable()){
// 若“接收就绪”,获取客户端连接
SocketChannel sChannel = ssChannel.accept();
// 切换成非阻塞模式
sChannel.configureBlocking(false);
// 将通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
}else if (sk.isReadable()){
// 获取当前选择器上“读就绪”状态的通道
SocketChannel sChannel = (SocketChannel) sk.channel();
// 读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = 0;
while((len = sChannel.read(buf)) >0 ){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
}
// 取消 SelectionKey
it.remove();
}
}
// 关闭通道
// ssChannel.close();
}
}
public class Aclient {
public static void main(String[] args) throws Exception{
// 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
// 切换成非阻塞模式
sChannel.configureBlocking(false);
// 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 发送数据给服务端
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String str = scanner.next();
buf.put((new Date().toString() + " " + str).getBytes());
buf.flip();
sChannel.write(buf);
buf.clear();
}
// 关闭通道
sChannel.close();
}
}
public class Areceive {
public static void main(String[] args) throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while(selector.select() > 0){
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()){
SelectionKey sk = it.next();
if(sk.isReadable()){
ByteBuffer buf = ByteBuffer.allocate(1024);
dc.receive(buf);
buf.flip();
System.out.println(new String(buf.array(),0,buf.limit()));
buf.clear();
}
}
it.remove();
}
}
}
public class Asend {
public static void main(String[] args) throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(1024);
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.next();
buf.put((new Date().toString() + " "+ str).getBytes());
buf.flip();
dc.send(buf,new InetSocketAddress("127.0.0.1",9898));
buf.clear();
}
dc.close();
}
}
public class Test {
public static void main(String[] args) throws IOException {
// 获取管道
Pipe pipe = Pipe.open();
// 将缓冲区中的数据写入管道
ByteBuffer buf = ByteBuffer.allocate(1024);
Pipe.SinkChannel sinkChannel = pipe.sink();
buf.put("通过单向管道发送数据".getBytes());
buf.flip();
sinkChannel.write(buf);
// 读取缓冲区中的数据
Pipe.SourceChannel sourceChannel = pipe.source();
buf.flip();
int len = sourceChannel.read(buf);
System.out.println(new String(buf.array(),0,len));
sinkChannel.close();
sourceChannel.close();
}
}