Java实现文件拷贝(二)

2014-11-24 02:56:01 · 作者: · 浏览: 9
dTime = System.currentTimeMillis();
System.out.println("copyByNioTransferFrom time consumed(buffer size no effect) : "
+ (endTime - startTime));
}
/**
* 使用FileChannel.transferTo()实现
* @throws FileNotFoundException
* @throws IOException
*/
private static void copyByNioTransferTo() throws FileNotFoundException,
IOException {
long startTime = System.currentTimeMillis();
RandomAccessFile fromFile = new RandomAccessFile(FROM_FILE, "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("G:/to2.rar", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel);
long endTime = System.currentTimeMillis();
System.out.println("copyByNioTransferTo time consumed(buffer size no effect) : "
+ (endTime - startTime));
}
/**
* 使用Channel, Buffer简单读写实现
* @throws IOException
*/
private static void coypByBufferRead() throws IOException {
long startTime = System.currentTimeMillis();
FileInputStream fin = new FileInputStream(FROM_FILE);
FileOutputStream fout = new FileOutputStream("G:/to3.rar");
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
while (true) {
buffer.clear();
int r = fcin.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcout.write(buffer);
}
long endTime = System.currentTimeMillis();
System.out.println("coypByBufferRead time consumed(buffer size take effect) : "
+ (endTime - startTime));
}
/**
* 使用连续内存的Buffer实现
* @throws IOException
*/
private static void coypByFastBufferRead() throws IOException {
long startTime = System.currentTimeMillis();
FileInputStream fin = new FileInputStream(FROM_FILE);
FileOutputStream fout = new FileOutputStream("G:/to4.rar");
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
while (true) {
buffer.clear();
int r = fcin.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcout.write(buffer);
}
long endTime = System.currentTimeMillis();
System.out.println("coypByFastBufferRead time consumed(buffer size take effect) : "
+ (endTime - startTime));
}
/**
* 使用文件内存映射实现
* @throws IOException
*/
private static void coypByMbb() throws IOException {
long startTime = System.currentTimeMillis();
FileInputStream fin = new FileInputStream(FROM_FILE);
RandomAccessFile fout = new RandomAccessFile("G:/to5.rar", "rw");
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
MappedByteBuffer mbbi = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
fcin.size());
MappedByteBuffer mbbo = fcout.map(FileChannel.MapMode.READ_WRITE, 0,
fcin.size());
mbbo.put(mbbi);
mbbi.clear();
mbbo.clear();
long endTime = System.currentTimeMillis();
System.out
.println("coypByMbb time consumed(buffer size no effect) : " + (endTime - startTime));
}
/**
* 使用传统IO的流读写方式实现
* @throws IOE