1、使用直接緩衝區完成文件的複製 ( 內存映射文件 )
JDK 1.7 後 提供
上面的 create 的話就是:
不存在就建立
存在的話就覆蓋..java
/**
* 2. 使用 直接緩衝區 完成文件的複製 (內存映射文件)
* 直接緩衝區 --> 只有 byte 支持
*/
@Test
public void test2(){
FileChannel inChannel = null;
FileChannel outChannle = null;
try {
inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
outChannle = FileChannel.open(Paths.get("3.jpg"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE\_NEW);
// 這個就是 內存映射文件
MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ\_ONLY, 0 , inChannel.size());
MappedByteBuffer outMappedBuf = outChannle.map(FileChannel.MapMode.READ\_WRITE, 0, inChannel.size());
// 上面的兩個內存映射文件都在 物理內存中....
// 如今的優勢, 只須要從緩衝區中讀寫操做..
byte[] dst = new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMappedBuf.put(dst);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outChannle != null){
try {
outChannle.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、 利用通道完成文件的複製 (非直接緩衝區的)
/\*\*
\* 1. 利用通道完成文件的複製 (非直接緩衝區的) \*/@Test
public void test1(){
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = new FileInputStream("1.jpg");
fos = new FileOutputStream("2.jpg");
// 1. 獲取通道
inChannel = fis.getChannel();
outChannel = fos.getChannel();
// 2. 分配指定大小的緩衝區.
ByteBuffer buf = ByteBuffer.allocate(1024);
// 3. 讀取數據
// 將 通道中的數據存入緩衝區中 while(inChannel.read(buf) != -1){
// 切換成讀取數據模式
buf.flip();
// 4. 寫入數據
// 將緩存區的數據寫入到 通道中 outChannel.write(buf);
// 清空緩衝區
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outChannel != null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3、通道之間的數據傳輸
/\*\*
\* 通道之間的數據傳輸 \*/@Test
public void test3(){
FileChannel inChannel = null;
FileChannel outChannle = null;
try {
inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
outChannle = FileChannel.open(Paths.get("4.jpg"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE\_NEW);
inChannel.transferTo(0, inChannel.size(), outChannle);
// 這個 outChannel 也行...
// outChannle.transferFrom(inChannel, 0, inChannel.size());
}catch (IOException e){
e.printStackTrace();
} finally {
if(inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outChannle != null){
try {
outChannle.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}