2012-02-16 20:03:04|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:Java, 文件操作|来源:唯设编程网
方法三:内存文件映射
public static long forImage(File f1, File f2) throws Exception { long time = new Date().getTime(); int length = 2097152; FileInputStream in = new FileInputStream(f1); RandomAccessFile out = new RandomAccessFile(f2, "rw"); FileChannel inC = in.getChannel(); MappedByteBuffer outC = null; MappedByteBuffer inbuffer = null; byte[] b = new byte[length]; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.force(); out.close(); return new Date().getTime() - time; } if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else { length = 20971520; } b = new byte[length]; inbuffer = inC.map(MapMode.READ_ONLY, inC.position(), length); inbuffer.load(); inbuffer.get(b); outC = out.getChannel().map(MapMode.READ_WRITE, inC.position(), length); inC.position(b.length + inC.position()); outC.put(b); outC.force(); } }
实现方法:跟伤2个例子不一样,这里写文件流没有使用管道而是使用内存文件映射(假设文件f2在内存中).在循环中从f1的管道中读取数据到字节数组里,然后在像内存映射的f2文件中写数据.(读文件没有使用文件景象,有兴趣的可以回去试试,,我就不试了,估计会更快)
方法四:管道-管道
public static long forChannel(File f1, File f2) throws Exception { long time = new Date().getTime(); int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); ByteBuffer b = null; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); return new Date().getTime() - time; } if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else length = 2097152; b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } }
这里实现方式与第3种实现方式很类似,不过没有使用内存影射.
下面是对49.3MB的文件进行拷贝的测试时间(毫秒)
Start Copy File... file size:50290KB
CopyFile:b1.rmvb mode:forChannel RunTime:3203
CopyFile:b1.rmvb mode:forImage RunTime:3328
CopyFile:b1.rmvb mode:copyFile RunTime:2172
CopyFile:b1.rmvb mode:copyFileNIO RunTime:1406
End Copy File!