Android 操纵File查看文件大小,清理文件

最近在开发android应用程序的时候,socket编程中需要将一个文件的大小传输到客户端,以便计算文件的传输速度和进度。这其中要判断文件夹大小,在网上查阅资料,将有代表的demo分享下:
 
package com.demo.file;
 
import java.io.File;
import java.text.DecimalFormat;
import java.io.FileInputStream;
 
public class GetFileSizeUtil
{
 
 private static GetFileSizeUtil instance;
 
 public GetFileSizeUtil()
 {
 
 }
 
 public static GetFileSizeUtil getInstance()
 {
  if (instance == null)
  {
   instance = new GetFileSizeUtil();
  }
 return instance;
 }
 
 
 public long getFileSizes(File f) throws Exception
 {
  long s = 0;
  if (f.exists())
  {
   FileInputStream fis = null;
   fis = new FileInputStream(f);
   s = fis.available();
  }
  else
  {
   f.createNewFile();
   System.out.println("文件不存在");
  }
  return s;
 }
 
 
 public long getFileSize(File f) throws Exception
 {
  long size = 0;
  File flist[] = f.listFiles();
  for (int i = 0; i < flist.length; i++)
  {
   if (flist.isDirectory())
   {
    size = size + getFileSize(flist);
   }
   else
   {
    size = size + flist.length();
   }
  }
  return size;
 }
 
 
 public String FormetFileSize(long fileS)
 {// 转换文件大小
  DecimalFormat df = new DecimalFormat("#.00");
  String fileSizeString = "";
  if (fileS < 1024)
  {
   fileSizeString = df.format((double) fileS) + "B";
  }
  else if (fileS < 1048576)
   {
    fileSizeString = df.format((double) fileS / 1024) + "K";
   }
   else if (fileS < 1073741824)
   {
    fileSizeString = df.format((double) fileS / 1048576) + "M";
   }
   else
   {
    fileSizeString = df.format((double) fileS / 1073741824) + "G";
   }
  return fileSizeString;
 }
 
 
 public long getlist(File f)
 {// 递归求取目录文件个数
  long size = 0;
  File flist[] = f.listFiles();
  size = flist.length;
  for (int i = 0; i < flist.length; i++)
  {
   if (flist.isDirectory())
   {
    size = size + getlist(flist);
    size--;
   }
  }
  return size;
 }
/**
	 * 清理缓存
	 */


	public void clear(File file) {
		File[] files = file.listFiles();
		if (files == null)
			return;
		for (File f : files) {
			f.delete();
		}
	}
 
}


你可能感兴趣的:(file大小)