dk1.4推出了java nio,加入了很多新的特性,sun也说nio的性能优于io,但是我使用中发现并非如此.io的copyfile代码public static void copyFile(File source, File dest) throws IOException { if(!dest.exists()) { dest.createNewFile(); } InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(dest); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if(in != null) { in.close(); } if(out != null) { out.close(); } } }nio代码public static void copyFile2(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } }这里没用使用,byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); }而是使用transferFrom,因为它是本地方法,优化过的.还可以使用 MappedByteBuffer public static void copyFileNio(File source, File dest) throws IOException { FileInputStream fi = new FileInputStream(source); FileChannel fic = fi.getChannel(); MappedByteBuffer mbuf = fic.map( FileChannel.MapMode.READ_ONLY, 0, source.length()); fic.close(); fi.close(); FileOutputStream fo = new FileOutputStream(dest); FileChannel foc = fo.getChannel(); foc.write(mbuf); foc.close(); fo.close(); }当时做的测试时,在linux下,对于小而文件,nio的速度远远高于io,大文件nio的性能要高于io.但是在win2k下,使用MappedByteBuffer的效率很低,比直接读流慢,大文件nio的性能不是很高. |