NIO中通道由 java.nio.channels 包定义的。Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据,Channel 只能与Buffer 进行交互。
实现通道的主要的类:
FileChannel (本地文件有关的)
Socket ,ServerSocket DatagramSocket (网络通讯相关)
1-针对支持通道的类提供了getChannel的方法:
本地: FileInputStream/FileOutPutStream RandomAccessFile
网络: Socket ServerSocket DatagramSocket
2.在jdk1.7中的NIO针对每种通道提供了open静态方法
3.在jdk1.7中Files工具类中提供了newByteChannel的方法
利用通道来进行文件的拷贝:
public class Demo03_TestChannel {
public static void main(String[] args) {
File src = new File("hook.txt");
File des = new File("hook2.txt");
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel channel = null;
FileChannel channel2 = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(des);
// 获取通道
channel = fis.getChannel();
channel2 = fos.getChannel();
// 创建缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 向通道中写
while (channel.read(buf) != -1) {
// 改变模式
buf.flip();
// 写出去
channel2.write(buf);
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
if (channel2 != null) {
try {
channel2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
利用map映射进行复制:
private static void test01() throws IOException{
//打开通道
FileChannel inChannel = FileChannel.open(Paths.get("src"),StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("des"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
//映射到map上
MappedByteBuffer inMapBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMapBuffer = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
byte[] b=new byte[inMapBuffer.limit()];
inMapBuffer.get(b);
outMapBuffer.put(b);
outChannel.close();
inChannel.close();
}
通道间的数据传输
private static void test02() throws IOException {
FileChannel inChannel =
FileChannel.open(Paths.get("src"),StandardOpenOption.READ);
FileChannel outChannel =
FileChannel.open(Paths.get("des"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
//通道间的数据传输
inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.close();
inChannel.close();
}