Java NIO Channel
来源:互联网 发布:网红开的淘宝店有哪些 编辑:程序博客网 时间:2024/06/15 04:45
Java NIO Channels are similar to streams with a few differences:
- You can both read and write to a Channels. Streams are typically one-way (read or write).
- Channels can be read and written asynchronously.
- Channels always read to, or write from, a Buffer.
As mentioned above, you read data from a channel into a buffer, and write data from a buffer into a channel. Here is an illustration of that:
Java NIO: Channels read data into Buffers, and Buffers write data into Channels
Channel Implementations
Here are the most important Channel implementations in Java NIO:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
The FileChannel
reads data from and to files.
The DatagramChannel
can read and write data over the network via UDP.
The SocketChannel
can read and write data over the network via TCP.
The ServerSocketChannel
allows you to listen for incoming TCP connections, like a web server does. For each incoming connection aSocketChannel
is created.
Basic Channel Example
Here is a basic example that uses a FileChannel
to read some data into aBuffer
:
import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class App {public static void main(String[] args) throws IOException {RandomAccessFile aFile = new RandomAccessFile("C:/Users/Jack/Desktop/new/access.log", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();}}
Notice the
buf.flip()
call. First you read into a Buffer. Then you flip it. Then you read out of it. I'll get into more detail about that in the next text aboutBuffer
's.link from: http://tutorials.jenkov.com/java-nio/channels.html
0 0
- Java NIO Channel
- Java NIO Socket Channel
- Java NIO(3-Channel)
- Java NIO Channel
- Java NIO笔记 Channel
- Java NIO Channel
- Java NIO--Channel
- java NIO Channel
- Java NIO (二) Channel
- Java NIO Channel
- Java NIO Channel
- java NIO-Channel
- Java NIO Channel
- Java NIO之Channel
- java nio channel
- Java NIO Channel tranfer
- Java NIO Channel
- java NIO Channel详解
- 深入理解SELinux SEAndroid(3最后部分)
- IOS 调取系统相册 ios9 图片模糊问题
- 家庭流媒体服务器(by quqi99)
- org.json的基本用法
- C语言基础 sizeof函数查看变量类型占多少字节
- Java NIO Channel
- ng-style用法
- 1.1 Writing a Simple C++ Program
- MySQL行级锁SELECT FOR UPDATE 和LOCK IN SHARE MODE区别
- centos删除文件空间不释放解决方法
- python练习3——请写一个密码安全性检查的脚本代码:check.py
- Android Studio 问题记录
- scrollview嵌套listview导致无法正常显示
- android studio 解决debug adb端口问题,亲身经历总结