import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_data = (EditText)findViewById(R.id.et_data);
//Environment.getDataDirectory(); /data
//一般下载不要用这个目录----内置存储
//Environment.getDownloadCacheDirectory(); //catch
//Environment.getExternalStorageDirectory();//mnt/sdcard
//Environment.getRootDirectory(); //System
//mnt/sdcard/music-dicm .....
//Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_)
}
/**
* 写sd卡
* @throws IOException
*/
public void saveData(View v) {
String data = et_data.getText().toString();
Log.i("tz","data:"+data);
//1,判断当前手机的sd卡是否正常挂载
//Environment.MEDIA_MOUNTED:sd存在 具有可读可写权限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//2,sd卡的目录对象
File sd_file = Environment.getExternalStorageDirectory();
//3,获取sd卡的路径(绝对路径 相对路劲)
String sd_path = sd_file.getAbsolutePath();
//4,创建文件保存数据
File file = new File(sd_file,"hehe.txt");
Toast.makeText(this, "sd_path:"+sd_path, 0).show();
//5,操作sd卡:需要权限--读/写
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(data.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
/**
* 读sd卡
*
*/
public void readData(View v){
FileInputStream fis = null;
try {
//1,判断当前手机的sd卡是否正常挂载
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//2,sd卡目录
File sd_file = Environment.getExternalStorageDirectory();
//3,创建文件
File file = new File(sd_file,"hehe.txt");
fis = new FileInputStream(file);
int len = 0;
byte[] buffers = new byte[1024];
//桶---装
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len=fis.read(buffers))!=-1){
baos.write(buffers, 0, len);
}
//把读出来的数据显示到EditText中
et_data.setText(baos.toString());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if (fis != null) {
try {
fis.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}
sd卡的读写权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>