java filechannel 性能_Java NIO FileChannel与FileOutputstream性能/实用性

我试图找出当我们使用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");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值