您的位置:首页 > 其它

第一个小应用:图片浏览器 之 四 读写SD卡

2016-03-13 13:39 429 查看

读取SD卡

权限配置:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etText;
private TextView tvShow;
//Environment.getExternalStorageDirectory();获取sd卡的目录
private File sdCardPath = Environment.getExternalStorageDirectory();
private String fileName = "Myfile";
//操作SD卡需要在AndroidManifest.xml中配置使用权限
//    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
//    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etText = (EditText) findViewById(R.id.etText);
tvShow = (TextView) findViewById(R.id.tvShow);
findViewById(R.id.btnWrite).setOnClickListener(this);
findViewById(R.id.btnRead).setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnWrite:
File file = new File(sdCardPath,fileName);
//检查是否存在sd卡,可能是你没有配置
if (!sdCardPath.exists()){
Toast.makeText(getApplicationContext(),"当前系统没有SD卡目录",Toast.LENGTH_SHORT).show();
return;
//如果没有sd卡,下面的动作都不做
}
if (!file.exists()){
try {
file.createNewFile();
Toast.makeText(getApplicationContext(),"文件创建成功",Toast.LENGTH_SHORT).show();
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
osw.write(etText.getText().toString());
Toast.makeText(getApplicationContext(),"文件写入完成",Toast.LENGTH_SHORT).show();
etText.setText("");
osw.flush();
fos.flush();
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

break;
case R.id.btnRead:
//检查是否存在sd卡,可能是你没有配置
if (!sdCardPath.exists()){
Toast.makeText(getApplicationContext(),"当前系统没有SD卡目录",Toast.LENGTH_SHORT).show();
return;
}
File fileRead = new File(sdCardPath,fileName);
if (fileRead.exists()){
try {
FileInputStream fis = new FileInputStream(fileRead);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] buffer = new char[fis.available()];
isr.read(buffer);
String strBuf = new String(buffer);
tvShow.setText(strBuf);
isr.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

break;

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: