/* * 一、通道:用于源节点与目标节点的连接.在Java NIO中负责缓冲区中的数据的传输。 * Channel本身不存储数据,需要配合缓冲区进行传输. * * 二、通道的主要实现类 * java.nio.channels.Channel接口: * FileChannel * //下面是用于网络的 * SocketChannel * ServerSocketChannel * DatagramChannel * 三、获取通道 * 1.Java针对支持通道的类提供了getChannel()方法 * FileInputStream/FileOutputStream * * Socket * ServerSocket * DatagramSocket * * */ public class TestChannel { //1.利用通道完成文件的复制 @Test public void test1() throws IOException{ 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); //将通道中的数据存入缓冲区中 inChannel读取数据放进buf中 while(inChannel.read(buf)!=-1){ buf.flip();//切换成读数据模式 //将缓冲区中的数据写入通道中 outChannel.write(buf); buf.clear();//清空缓冲区 } outChannel.close(); inChannel.close(); fos.close(); fis.close(); } }
NIO利用通道来进行数据传输
猜你喜欢
转载自blog.csdn.net/jasonkwan12/article/details/79961240
今日推荐
周排行