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();
}
}