Environment: 獲取系統中的存儲設備信息
getRootDirectory(): 獲取系統空間文件對象。
通過getBlockSize()方法獲取出來的值,是以字節做單位。
下面是代碼:
package Getystem_file_info.demo;
import java.io.File;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv1,tv2,tv3,tv4;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findVeiw();
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File externalStoragePath = Environment.getExternalStorageDirectory();
StatFs statFs = new StatFs(externalStoragePath.getPath());
int blockSize = statFs.getBlockSize();
int blockCount = statFs.getBlockCount();
int availableBlocks = statFs.getAvailableBlocks();
int freeBlocks = statFs.getFreeBlocks();
String[] blockSizes = sizeFormat(blockCount*blockSize);
String[] availableSize = sizeFormat(availableBlocks*blockSize);
String[] freebleSize = sizeFormat(freeBlocks*blockSize);
tv1.setText("外儲設備總大小:"+ blockSizes[0] + blockSizes[1] );
tv2.setText("外儲設備可用大小:"+ availableSize[0] + availableSize[1] );
tv3.setText("外儲設備freeBlocks大小:"+ freebleSize[0] + freebleSize[1] );
}
}
private void findVeiw() {
tv1 = (TextView) this.findViewById(R.id.textview1);
tv2 = (TextView) this.findViewById(R.id.textview2);
tv3 = (TextView) this.findViewById(R.id.textview3);
}
String[] sizeFormat(long size) {
String str = "B";
if(size >= 1024) {
str = "KB";
size /= 1024;
if(size >= 1024) {
str = "MB";
size /= 1024;
}
}
DecimalFormat format = new DecimalFormat();
format.setGroupingSize(3);
String[] result = new String[2];
result[0] = format.format(size);
result[1] = str;
return result;
}
}