您的位置:首页 > 编程语言 > Java开发

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

2015-08-14 17:25 671 查看
刚才使用如下代码进行测试,得到了如下下的结果!!

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

装饰越多越慢呀。

在读超大文件的时候会有坑,见这里:/article/2129100.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: