Home > Java > javaTutorial > body text

How to use java Channel

WBOY
Release: 2023-04-19 11:22:02
forward
2656 people have browsed it

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();                  //"清空"缓冲区
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!