channel代码示例
package cn.com.github.immortals;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.junit.Test;
/** * * @author 潘琢文 * */
public class TestChannel {
// 分散和聚集
@Test
public void test4() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
// 1. 获取通道
FileChannel channel1 = raf1.getChannel();
// 2. 分配指定大小的缓冲区
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
// 3. 分散读取
ByteBuffer[] bufs = { buf1, buf2 };
channel1.read(bufs);
for (ByteBuffer byteBuffer : bufs) {
byteBuffer.flip();
}
System.out.println(new String(bufs[0].array(), 0, bufs[0].limit()));
System.out.println("-----------------");
System.out.println(new String(bufs[1].array(), 0, bufs[1].limit()));
// 4. 聚集写入
RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
FileChannel channel2 = raf2.getChannel();
channel2.write(bufs);
}
/** * 利用channel复制文件 * * @throws IOException */
@Test
public void testChannel() throws IOException {
FileInputStream ins = new FileInputStream(new File("D:/大话西游之大圣娶亲[国语版]_bd.mp4"));
FileOutputStream fos = new FileOutputStream(new File("D:/大话西游之大圣娶亲[国语版]_bd_copy.mp4"));
FileChannel in = ins.getChannel();
FileChannel out = fos.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
while (in.read(buf) != -1) {
buf.flip();
out.write(buf);
buf.clear();
}
ins.close();
fos.close();
in.close();
out.close();
}
/** * channel的直接缓冲区复制文件 * * @throws IOException */
@Test
public void testChannel2() throws IOException {
FileChannel in = FileChannel.open(Paths.get("D:/大话西游之大圣娶亲[国语版]_bd.mp4"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("D:/大话西游之大圣娶亲[国语版]_bd_copy.mp4"), StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
in.transferTo(0, in.size(), out);
in.close();
out.close();
}
@Test
public void testChannel3() throws IOException {
FileChannel in = FileChannel.open(Paths.get("D:/大话西游之大圣娶亲[国语版]_bd.mp4"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("D:/大话西游之大圣娶亲[国语版]_bd_copy.mp4"), StandardOpenOption.CREATE,
StandardOpenOption.WRITE, StandardOpenOption.READ);
MappedByteBuffer inBuffer = in.map(MapMode.READ_ONLY, 0, in.size());
MappedByteBuffer outBUffer = out.map(MapMode.READ_WRITE, 0, in.size());
byte[] dst = new byte[inBuffer.limit()];
inBuffer.get(dst);
outBUffer.put(dst);
in.close();
out.close();
}
}