我正在尝试弄清楚,当我们使用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");
}
}
发布于 2009-10-23 03:58:52
我测试了FileInputStream和FileChannel在解码base64编码文件方面的性能。在我的实验中,我测试了相当大的文件,传统的io总是比nio快一点。
由于几个io相关类中的同步开销,FileChannel在jvm的早期版本中可能具有优势,但现代jvm在删除不需要的锁方面做得很好。
发布于 2013-04-23 00:57:54
如果您没有使用transferTo特性或非阻塞特性,您将不会注意到传统IO和NIO(2)之间的差异,因为传统IO映射到NIO。
但是,如果您可以使用transferFrom/To之类的NIO功能,或者想要使用Buffers,那么NIO当然是可行的。
发布于 2009-10-22 14:26:56
我的经验是,NIO在处理小文件时要快得多。但是当涉及到大文件时,FileInputStream/FileOutputStream要快得多。
https://stackoverflow.com/questions/1605332
复制相似问题