zoukankan      html  css  js  c++  java
  • 文件大小

    1.使用File的length()方法

    public static void main(String[] args) {
    File f= new File("D:\CentOS-6.5-x86_64-bin-DVD1.iso");
    if (f.exists() && f.isFile()){
    logger.info(f.length());
    }else{
    logger.info("file doesn't exist or is not a file");
    }
    }

    我们看一下输出结果:4467982336 

    --------------------------

    接下来我们看一下通过FileInputStream来获取的文件大小:

    public static void main(String[] args) {
    FileInputStream fis= null;
    try{
    File f= new File("D:\CentOS-6.5-x86_64-bin-DVD1.iso");
    fis= new FileInputStream(f);
    logger.info(fis.available());
    }catch(Exception e){
    logger.error(e);
    } finally{
    if (null!=fis){
    try {
    fis.close();
    } catch (IOException e) {
    logger.error(e);
    }
    }
    }
    }

    下面是运行结果:

    2147483647

    这个结果是不是很眼熟?它是Integer.MAX_VALUE,也就是有符号整型能表示的最大数值。

    那么换算成熟悉的单位,这种方式获取的文件大小是多大呢?

    约等于2GB,这显然不是正确的结果。

    究其原因,File的length()方法返回的类型为long,long型能表示的正数最大值为:9223372036854775807,折算成最大能支持的文件大小为:8954730132868714 EB字节,这个量级将在人类IT发展史上受用很多很多年,而FileInputStream的avaliable()方法返回值是int,在之前也介绍了最大的表示范围,所能支持的最大文件大小为:1.99GB,而这个量级我们现在很容易就达到了。

    2014年3月31日补充:

    针对流式方法读取大文件大小也不是不可行,只是不能再使用传统的Java.io.*下的包了,这里要用到java.nio.*下的新工具——FileChannel。下面我们来看下示例代码:

    public static void main(String[] args) {
    FileChannel fc= null;
    try {
    File f= new File("D:\CentOS-6.5-x86_64-bin-DVD1.iso");
    if (f.exists() && f.isFile()){
    FileInputStream fis= new FileInputStream(f);
    fc= fis.getChannel();
    logger.info(fc.size());
    }else{
    logger.info("file doesn't exist or is not a file");
    }
    } catch (FileNotFoundException e) {
    logger.error(e);
    } catch (IOException e) {
    logger.error(e);
    } finally {
    if (null!=fc)){
    try{
    fc.close();
    }catch(IOException e){
    logger.error(e);
    }
    }
    }
    }

    使用FileChannel后得到的结果与第一种情况吻合,准确地描述了文件的准确大小。

    这里也同样提醒各位技术同仁,涉及到大文件读取的时候,对int类型的数据一定要留个心,以免出现隐藏的bug,定位起来很困难。

    -------------------------

    现在做一个上传文件不让他超过5M的方法 怎么实现呢
    long fileSize = file.getSize();
    返回的是long
    if(){
    }
    判断条件里怎么写啊

    返回的是字节长度,1M=1024k=1048576字节 也就是if(fileSize<5*1048576)就好了
  • 相关阅读:
    learning.py报错
    Swift与OC的相互调用
    微信小程序地图之逆地理编码
    微信小程序-滑动视图注意事项
    animate.css动画种类
    利用WKWebView实现js与OC交互注意事项
    jquey下eq()的使用注意事项
    如何判断html页面停止滚动?
    git 常见报错
    openresty中http请求body数据过大的处理方案
  • 原文地址:https://www.cnblogs.com/qq3245792286/p/6242220.html
Copyright © 2011-2022 走看看