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);
    }
}

 

posted @ 2016-10-31 11:05  life_start  阅读(485)  评论(0编辑  收藏  举报