java 获取文件长度的几种方法的效率比较

刚才使用如下代码进行测试,得到了如下下的结果!!

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by yangjunlin on 8/14/15.
 */
public class FileTest
{
    public static void main(String[] dd)
    {
        Path path = Paths.get("/home/yangjunlin/Downloads/ubuntu-14.04.2-desktop-amd64.iso");
        System.out.println(path.getFileName());

        long begin1 = System.nanoTime();
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(path.toFile(), "rw"))
        {
            System.out.println("RandomAccessFile length: " + randomAccessFile.length());
            System.out.println("RandomAccessFile nanoTime: " + (System.nanoTime() - begin1));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        long begin2 = System.nanoTime();
        System.out.println("File length: " + path.toFile().length());
        System.out.println("File nanoTime: " + (System.nanoTime() - begin2));

        long begin3 = System.nanoTime();
        try (FileInputStream fileInputStream = new FileInputStream(path.toFile()))
        {
            System.out.println("FileInputStream length: " + fileInputStream.available());
            System.out.println("FileInputStream nanoTime: " + (System.nanoTime() - begin3));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        long begin4 = System.nanoTime();
        try (FileChannel fileChannel = new FileInputStream(path.toFile()).getChannel())
        {
            System.out.println("FileChannel length: " + fileChannel.size());
            System.out.println("FileChannel nanoTime: " + (System.nanoTime() - begin4));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

结果如下:

ubuntu-14.04.2-desktop-amd64.iso
RandomAccessFile length: 1044381696
RandomAccessFile nanoTime: 449054
File length: 1044381696
File nanoTime: 80385
FileInputStream length: 1044381696
FileInputStream nanoTime: 108946
FileChannel length: 1044381696
FileChannel nanoTime: 3220354


装饰越多越慢呀。

在读超大文件的时候会有坑,见这里:http://blog.csdn.net/chaijunkun/article/details/22387305

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值