zoukankan      html  css  js  c++  java
  • 21 获取文件大小的方法

    package com.hikvision.java.file.filesize;/*
     * Project: HbaseTest
     * Address: http://www.hikvision.com
     * Date: 2016/10/31 10:02
     * Description: This content is limited to use in Hikivision Research Institude, forwarding is prohibited.
     *
     * Copyright (c) 2016. 2002-2016@Hangzhou Hikvision Digital Technology Co., Ltd. All Right Reservered.
     */
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    
    /**
    获取文件大小,的三种方式
     字节,KB ,MB  : bytes,kilobytes,megabytes
     */
    public class ObtainFileSize {
        public static final Logger LOG= LoggerFactory.getLogger(ObtainFileSize.class);
    
        public static void main(String[] args) {
            String filePath="F:\test\fileSize.txt";
            if(!new File(filePath).exists()){
            }else{
                long fileSize=getFileSizeMethod1(filePath);
                LOG.info("the size of {} is {} bytes",filePath,fileSize);
                LOG.info("the size of {} is {} MB",filePath,byteToMB(fileSize));
            }
        }
    
        /**
         * @param FilePath 获取文件大小 单位字节
         * @return
         */
        public static long getFileSizeMethod1(String FilePath){
            return new File(FilePath).length();
        }
    
        /**
         *
         * @param FilePath 获取文件大小 单位字节 最大2G
         * @return
         * @throws IOException
         */
        public static int getFileSizeMethod2(String FilePath) throws IOException {
            return new FileInputStream(FilePath).available();
        }
    
        /**
         *
         * @param FilePath 获取文件大小 单位字节
         * @return
         * @throws IOException
         */
        public static long getFileSizeMethod3(String FilePath) throws IOException {
            return new FileInputStream(FilePath).getChannel().size();
        }
    
        /**
         * 字节转成KB
         * @param size
         * @return
         */
        public static double byteToKB(long size){
            return size/1024.0;
        }
    
        public static double byteToMB(long size){
            return size/(1024*1024.0);
        }
    }
  • 相关阅读:
    sql存储过程简单教程
    深入揭示Web 2.0核心技术——混搭
    Struts 2创始人Patrick Lightbody看《精通Struts 2:Web 2.0开发实战 》
    深入全面阐释Struts 2的方方面面
    设计原本如此简单
    掌握ASP.NET技术之捷径
    Struts 2创始人Patrick Lightbody作序推荐
    Struts 2权威著作
    Amazon超级畅销书之《C#与.NET 3.5高级程序设计(第4版)》
    Web开发领域最热门的话题之混搭
  • 原文地址:https://www.cnblogs.com/yangh2016/p/6015125.html
Copyright © 2011-2022 走看看