android点滴(3)之获取SDCard信息

 

主要使用Environment,StatFS两个类。

Environment:Provides access to environment variables

StatFS:Retrieve overall information about the space on a filesystem. This is a Wrapper for Unix statfs().

 

package cody.sdcard.info;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;

public class SDCardInfo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
       
        File file = Environment.getExternalStorageDirectory();
        System.out.println(file.getPath());
        StatFs statFs = new StatFs(file.getPath());
       
        int availBlocks = statFs.getAvailableBlocks();
        int totalBlocks = statFs.getBlockCount();
        int freeBlocks = statFs.getFreeBlocks();
        int blockSize = statFs.getBlockSize();
       
        String availSize = getSize(availBlocks * blockSize);
        String totalSize = getSize(totalBlocks * blockSize);
        String freeSize = getSize(freeBlocks * blockSize);
       
        System.out.println("total  " + totalSize);
        System.out.println("available  " + availSize);
        System.out.println("free  " + freeSize);
    }
   
    final int onek = 1024;
    final int onem = 1024 * onek;
    final int oneg = 1024 * onem;
   
    String getSize(int size){
     String str;
     float sizeb;
     if(size > oneg){
      str = "GB";
      sizeb = ((float)size) / oneg;
     }else if(size > onem){
      str = "MB";
      sizeb = ((float)size) / onem;
     }else if(size > onek){
      str = "KB";
      sizeb = ((float)size) / onek;
     }else{
      str = "B";
      sizeb = size;
     }
     
     sizeb = Math.round(sizeb * 10) * 1.0f  / 10;
     
     return sizeb + str;
    }
}

Logcat中查看结果:

09-21 09:37:55.771: INFO/System.out(661): /mnt/sdcard
09-21 09:37:55.771: INFO/System.out(661): total  510.0MB
09-21 09:37:55.781: INFO/System.out(661): available  510.0MB
09-21 09:37:55.781: INFO/System.out(661): free  510.0MB

 

 

 

 

 

 

 


 

你可能感兴趣的:(android)