1 package com.lidaochen.getsdcardspace; 2 3 import android.os.Environment; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.widget.EditText; 7 import android.widget.TextView; 8 9 import java.io.File; 10 import java.util.Formatter; 11 12 public class MainActivity extends AppCompatActivity { 13 private TextView et_total; 14 private TextView et_useAble; 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_main); 19 // 1.找到两个EditText控件 20 et_total = (TextView)findViewById(R.id.et_total); 21 et_useAble = (TextView)findViewById(R.id.et_useAble); 22 // 2.获取SD卡总大小和可用空间 23 File file = Environment.getExternalStorageDirectory(); 24 long totalSpace = file.getTotalSpace(); // 总大小 25 long useAbleSpace = file.getUsableSpace(); // 可用空间大小 26 // 3.展示到TextView上 27 et_total.setText("总大小:" + String.format("%.2f", (double)totalSpace / (1024 * 1024 * 1024)) + "GB"); 28 et_useAble.setText("可用空间:" + String.format("%.2f", (double)useAbleSpace / (1024 * 1024 * 1024)) + "GB"); 29 } 30 }