package com.hp.buffer;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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;
public class TextChannel {
@Test //获得通道方法一:用getChannel()方法(非直接缓冲区)
public void text1() throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
long start = System.currentTimeMillis();
try {
//输入输出流
fis = new FileInputStream("D:\\6.jpg");
fos = new FileOutputStream("D:\\8.jpg");
//通道
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//把通道里面的数据,读出来,放缓冲区里面
while(inChannel.read(buffer)!= -1) {
//把缓冲区里面的数据,写入,到通道里面
buffer.flip();
outChannel.write(buffer);
buffer.clear();//清空缓存区
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//对通道和流进行关闭
if(outChannel!=null) {
outChannel.close();
}
if(inChannel!=null) {
outChannel.close();
}
if(fos!=null) {
fos.close();
}
if(fis!=null) {
fis.close();
}
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
//获得通道方法二:静态open()方法,获取FileChannel对象,
//(直接缓冲区:不用写在应用程序的内存里面,直接写在物理地址上面)
@Test
public void test2() throws Exception {
FileChannel inChannel = FileChannel.open(Paths.get("D:\\6.jpg"), StandardOpenOption.READ);
MappedByteBuffer inmap = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
FileChannel outChannel = FileChannel.open(Paths.get("D:\\9.jpg"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);
MappedByteBuffer outmap = outChannel.map(MapMode.READ_WRITE , 0, inChannel.size());
long start = System.currentTimeMillis();
//对缓冲区域的数据进行操作
byte[] dst = new byte[inmap.limit()];
inmap.get(dst);
outmap.put(dst);
outChannel.close();
inChannel.close();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
//transferTo() /transferForm() (直接缓冲区)
@Test
public void test3() throws Exception {
FileChannel inFile = FileChannel.open(Paths.get("D:\\6.jpg"), StandardOpenOption.READ);
FileChannel outFile = FileChannel.open(Paths.get("D:\\10.jpg"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
inFile.transferTo(0, inFile.size(), outFile);
outFile.close();
inFile.close();
}
@Test //从流中获取通道,采用allocateDirect方式(直接缓冲区)
public void test4() throws Exception {
FileChannel inFile = FileChannel.open(Paths.get("D:\\6.jpg"),
StandardOpenOption.READ);
FileChannel outFile = FileChannel.open(Paths.get("D:\\11.jpg"),
StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
ByteBuffer buffer = ByteBuffer.allocateDirect((int)inFile.size());
inFile.read(buffer);
buffer.flip(); //切换
outFile.write(buffer);
outFile.close();
inFile.close();
}
}