- package com.ghb.crp.file;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.nio.ByteBuffer;
- import java.nio.channels.FileChannel;
- public class FileCopy {
- public static String src = "f://ss.rmvb";
- public static String dist = "f://ss2.rmvb";
- /**
- * @param args
- */
- public static void main(String[] args) {
- long start = System.currentTimeMillis();
- copyNew();
- long end = System.currentTimeMillis();
- System.out.println("nio 用時: " + (end - start));
- long start2 = System.currentTimeMillis();
- copyOld();
- end = System.currentTimeMillis();
- System.out.println("io 用時: " + (end - start2));
- }
- public static void copyOld() {
- File srcFile = new File(src);
- File distFile = new File(dist);
- if (distFile.exists()) {
- distFile.delete();
- }
- try {
- FileInputStream fin = new FileInputStream(srcFile);
- BufferedInputStream buffIn = new BufferedInputStream(fin);
- FileOutputStream fout = new FileOutputStream(distFile);
- BufferedOutputStream buffout = new BufferedOutputStream(fout);
- byte[] bytes = new byte[1024];
- while (buffIn.read(bytes) > 0) {
- buffout.write(bytes);
- }
- fin.close();
- buffIn.close();
- fout.close();
- buffout.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void copyNew() {
- try {
- File srcFile = new File(src);
- File distFile = new File(dist);
- if (distFile.exists()) {
- distFile.delete();
- }
- FileInputStream fin = new FileInputStream(srcFile);
- FileOutputStream fout = new FileOutputStream(distFile);
- FileChannel inChannel = fin.getChannel();
- FileChannel outChannel = fout.getChannel();
- int ByteBufferSize = 1024 * 100;
- ByteBuffer buff = ByteBuffer.allocate(ByteBufferSize);
- while (inChannel.read(buff) > 0) {
- buff.flip();
- if (inChannel.position() == inChannel.size()) {// 判斷是不是最後一段數據
- int lastRead = (int) (inChannel.size() % ByteBufferSize);
- byte[] bytes = new byte[lastRead];
- buff.get(bytes, 0, lastRead);
- outChannel.write(ByteBuffer.wrap(bytes));
- buff.clear();
- } else {
- outChannel.write(buff);
- buff.clear();
- }
- }// 這個使用FileChannel 自帶的複製
- // outChannel.transferFrom(inChannel, 0, inChannel.size());
- outChannel.close();
- inChannel.close();
- fin.close();
- fout.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }