1. Description
Channel is an object through which data can be read and written. It can be viewed as a stream in IO. But compared with streams, it has some differences:
Channel is bidirectional and can be read or written, while streams are one-way.
Channel can be read and written asynchronously.
Channel reading and writing must go through the buffer object.
2. Example
Use channels and indirect buffers to complete.
FileInputStream fis=null; //引用 FileOutputStream fout=null; FileChannel channel=null; //通道引用 FileChannel outchannel=null; try { fis = new FileInputStream("sb.jpg"); //源文件 fout = new FileOutputStream("bb.jpg"); //目标文件 channel = fis.getChannel(); //获取连接源文件的通道 outchannel = fout.getChannel(); //获取连接目标文件的通道 //指定缓冲区 非直接缓冲区 ByteBuffer buffer=ByteBuffer.allocate(1024); //创建缓冲区 用来传输数据 while(channel.read(buffer)!=-1) //从连接源文件的管道读取数据到缓冲区 { //将缓冲区反转 buffer.flip(); outchannel.write(buffer); //将缓冲区中的数据写入连接到目标文件的管道 buffer.clear(); //"清空"缓冲区 }
The above is the detailed content of How to use java Channel. For more information, please follow other related articles on the PHP Chinese website!