private static void channelCopy(ReadableByteChannel src,WritableByteChannel dest) throws IOException{
ByteBuffer buffer=ByteBuffer.allocate(10*1024);
while(src.read(buffer)!=-1){
buffer.flip();
while(buffer.hasRemaining()){
dest.write(buffer);
}
buffer.clear();
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ReadableByteChannel source=Channels.newChannel(System.in);
WritableByteChannel dest=Channels.newChannel(System.out);
ChannelCopy.channelCopy(source, dest);
source.close();
dest.close();
}
本文介绍了如何利用Java中的Channel API实现高效的文件复制操作,通过ChannelCopy方法将标准输入流的内容复制到标准输出流,展示了读取、翻转、写入的流程,以及关闭资源的正确实践。
575

被折叠的 条评论
为什么被折叠?



