我试图弄清楚,当我们使用nio FileChannel
与常规的FileInputStream/FileOuputStream
方式将文件读写到文件系统时,性能(或优势)是否存在任何差异。我观察到,在我的机器上,两者的性能都相同,而且FileChannel
速度也慢了很多倍。请问您可以比较这两种方法的更多详细信息。这是我使用的代码,正在测试的文件在左右350MB
。如果我不考虑随机访问或其他此类高级功能,是否可以将基于NIO的类用于文件I / O是一个好选择吗?
package trialjavaprograms;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class JavaNIOTest {
public static void main(String[] args) throws Exception {
useNormalIO();
useFileChannel();
}
private static void useNormalIO() throws Exception {
File file = new File("/home/developer/test.iso");
File oFile = new File("/home/developer/test2");
long time1 = System.currentTimeMillis();
InputStream is = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(oFile);
byte[] buf = new byte[64 * 1024];
int len = 0;
while((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
fos.close();
is.close();
long time2 = System.currentTimeMillis();
System.out.println("Time taken: "+(time2-time1)+" ms");
}
private static void useFileChannel() throws Exception {
File file = new File("/home/developer/test.iso");
File oFile = new File("/home/developer/test2");
long time1 = System.currentTimeMillis();
FileInputStream is = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(oFile);
FileChannel f = is.getChannel();
FileChannel f2 = fos.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(64 * 1024);
long len = 0;
while((len = f.read(buf)) != -1) {
buf.flip();
f2.write(buf);
buf.clear();
}
f2.close();
f.close();
long time2 = System.currentTimeMillis();
System.out.println("Time taken: "+(time2-time1)+" ms");
}
}
transferTo
/transferFrom
在复制文件时更为常规。不管使用哪种技术都不会使您的硬盘驱动器更快或更慢,尽管我猜测如果一次读取小块数据并导致磁头花费大量时间寻找,可能会出现问题。