package cn.sohu.com;
//1 查看SDCard相关信息的主要使用到的是StatFs类,没有其余难点
//2 从SDCard中读取txt文件要注意
// 第一:txt文件应该要按照UTF-8保存的.因为默认的是ANSI编码的!!!!!
// 第二:不能使用openFileInput(filePath)方法获取输入流.因为此方法的参数要求不能含有路径分隔符.
// 若这么做,报错:………………………………………………cannot contain path separator
//
//
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class TestSDCardActivity extends Activity {
private Button SDbutton;
private Button Filebutton;
private TextView textView;
private EditText editText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SDbutton=(Button) findViewById(R.id.Button1);
Filebutton=(Button) findViewById(R.id.Button2);
textView=(TextView) findViewById(R.id.textView);
SDbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断是否安装SDCard
File SDFile=Environment.getExternalStorageDirectory();
StatFs statFs=new StatFs(SDFile.getPath());
long blockSize=statFs.getBlockSize();//块容量
float blocksCount=statFs.getBlockCount();//块数量
int sizeM=(int) ((blockSize*blocksCount)/1024/1024);//总容量
long ableBlocks=statFs.getAvailableBlocks();//可用容量
int percent=(int) ((ableBlocks/blocksCount)*100);//可用百分比
textView.setText("SDCard使用情况如下:\n"+"blockSize="+blockSize+",totalBlocks="+blocksCount+",sizeM="+sizeM+",ableBlocks="+ableBlocks+"\n"+"使用率:\n"+percent+"%");
}else{
Toast.makeText(getApplicationContext(), "未找到SDCard", 1).show();
}
}
});
Filebutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
editText =(EditText) findViewById(R.id.editeView);
String fileName=editText.getText().toString();
String filePath=Environment.getExternalStorageDirectory().toString()+"/"+fileName;
try {
String result=read(filePath);
Log.i("Tag", "result="+result);
textView.setText(result);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public String read(String filePath) throws Exception{
//openFileInput方法的参数cannot contain path separator
File file=new File(filePath);
FileInputStream inputStream=new FileInputStream(file);
//FileInputStream inputStream=TestSDCardActivity.this.openFileInput(filePath);//注意这句代码!!!!!
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte [] b=new byte[1024];
int len=0;
while((len=inputStream.read(b))!=-1){
outputStream.write(b, 0, len);
Log.i("Tag", "len="+len);
}
outputStream.flush();
String result=outputStream.toString("UTF-8");
outputStream.close();
inputStream.close();
return result;
}
}
Android利用StatFs查看SDCard物理信息
最新推荐文章于 2021-02-16 17:57:48 发布