//测试代码, 用来验证内存映射文件、使用缓冲及流的文件读写的效率。可见内存映射文件的效率最高。
package com.nio.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MappedFile {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
long start ;
start = System.nanoTime();
FileCopyBuffer("G:\\jdk-6u22-linux-i586.bin", "I:\\云相关2.rar");
System.out.println((System.nanoTime() - start) / (float) 1000000000);
start = System.nanoTime();
FileCopyStream("G:\\btrace-bin.tar.gz", "I:\\云相关2.rar");
System.out.println((System.nanoTime() - start) / (float) 1000000000);
start = System.nanoTime();
FileCopyMaped("G:\\jdk-6u22-linux-i586.bin", "I:\\云相关2.rar");
System.out.println((System.nanoTime() - start) / (float) 1000000000);
}
private static void FileCopyMaped(String source, String target) {
FileInputStream in;
FileOutputStream out;
try {
in = new FileInputStream(source);
FileChannel inc = in.getChannel();
MappedByteBuffer buffer = inc.map(FileChannel.MapMode.READ_ONLY, 0,
inc.size());
out = new FileOutputStream(target);
FileChannel outc = out.getChannel();
outc.write(buffer);
inc.close();
outc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void FileCopyBuffer(String source, String target) {
FileInputStream in;
FileOutputStream out;
try {
in = new FileInputStream(source);
out = new FileOutputStream(target);
FileChannel inc = in.getChannel();
FileChannel outc = out.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
int tmp = inc.read(buffer);
while (tmp > 0) {
buffer.flip();
outc.write(buffer);
buffer.clear();
tmp = inc.read(buffer);
}
inc.close();
outc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void FileCopyStream(String source, String target) {
FileInputStream in;
FileOutputStream out;
try {
in = new FileInputStream(source);
out = new FileOutputStream(target);
int tmp = in.read();
while (tmp !=-1) {
out.write(tmp);
tmp = in.read();
}
out.flush();
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Buffer的拷贝文件大小:83761756,读写时间:1.3592848
使用流的拷贝文件大小:655656,读写时间:6.982578
使用内存映射文件拷贝文件大小:83761756,读写时间:1.0513209
可见使用内存映射文件的方式进行读写操作效率要高于Buffer的,而流操作是最耗时的(每次读写都要执行一次IO)。
本文通过测试不同方法拷贝文件的效率,对比了使用内存映射文件、缓冲区及直接流读写的方式。结果显示,内存映射文件的读写速度最快。
6879

被折叠的 条评论
为什么被折叠?



