import java.nio.*;
import java.nio.channel.*;
import java.io.*;
public static void copy(File source, File dest) throws IOException {
FileChannel in = null, out = null;
try {
in = new FileInputStream(source).getChannel();
out = new FileOutputStream(dest).getChannel();
long size = in.size();
MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
out.write(buf);
if (in != null) in.close();
if (out != null) out.close();
}
}
import java.nio.*; import java.nio.channel.*; import java.io.*; public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } }
谈谈MappedByteBuffer
JDK1.4中加入了一个新的包:NIO(java.nio.*).这个库最大的功能就是增加了对异步套接字的支持.
其实在其他语言中,包括在最原始的SOCKET实现(BSD SOCKET),这是一个早有的功能:异步回调读/写事件,
通过选择器动态选择感兴趣的事件,等等.不过好在SUN终于也开始支持它了.
我想这也是开放的好处之一吧(NIO是作为JSR-51项目引入的).
这里简单讲一下操作流程:
通过把一个套接字通道(SocketChannel)注册到一个选择器(Selector)中,不时调用后者的选择(select)方法就能返回
满足的选择键(SelectionKey),键中包含了SOCKET事件信息.
异步套接字对服务器程序来说更�