首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java NIO FileChannel与FileOutputstream性能/可用性的对比

Java NIO FileChannel与FileOutputstream性能/可用性的对比
EN

Stack Overflow用户
提问于 2009-10-22 14:21:26
回答 3查看 116.1K关注 0票数 172

我正在尝试弄清楚,当我们使用nio FileChannel和普通FileInputStream/FileOuputStream来读写文件系统时,在性能(或优点)上是否有什么不同。我观察到,在我的机器上,两者的性能处于相同的水平,而且很多时候FileChannel的方式要慢一些。我可以知道这两种方法比较的更多细节吗?这是我使用的代码,我正在测试的文件是关于350MB的。如果我不考虑随机访问或其他类似的高级功能,那么使用基于NIO的类进行文件I/O是否是一个好的选择?

代码语言:javascript
复制
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");
    }
}
EN

回答 3

Stack Overflow用户

发布于 2009-10-23 03:58:52

我测试了FileInputStream和FileChannel在解码base64编码文件方面的性能。在我的实验中,我测试了相当大的文件,传统的io总是比nio快一点。

由于几个io相关类中的同步开销,FileChannel在jvm的早期版本中可能具有优势,但现代jvm在删除不需要的锁方面做得很好。

票数 3
EN

Stack Overflow用户

发布于 2013-04-23 00:57:54

如果您没有使用transferTo特性或非阻塞特性,您将不会注意到传统IO和NIO(2)之间的差异,因为传统IO映射到NIO。

但是,如果您可以使用transferFrom/To之类的NIO功能,或者想要使用Buffers,那么NIO当然是可行的。

票数 2
EN

Stack Overflow用户

发布于 2009-10-22 14:26:56

我的经验是,NIO在处理小文件时要快得多。但是当涉及到大文件时,FileInputStream/FileOutputStream要快得多。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1605332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档