第一个小应用:图片浏览器 之 四 读写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; } } }
相关文章推荐
- test一下博客怎么写
- hdu3033I love sneakers!【分组背包】每组至少取一个
- iOS9中如何在日历App中创建一个任意时间之前开始的提醒(二)
- iOS9中如何在日历App中创建一个任意时间之前开始的提醒(二)
- 安卓5.0蓝牙低功耗 代码
- 第三周项目-个人所得税计算器
- CABasicAnimation的基本使用方法(移动·旋转·放大·缩小)
- iOS9中如何在日历App中创建一个任意时间之前开始的提醒(二)
- 正在编译转换: 未能找到元数据文件 EntityFramework.dll
- Java awt项目开发
- java的多态
- CATransition 的初级应用及type属性
- 单元测试
- 子线程更新UI
- 剑指offer-二进制中1的个数
- 教你写Http框架(二)——三个例子带你深入理解AsyncTask
- 内联函数 —— C 中关键字 inline 用法解析
- LintCode: Binary Tree Inorder Traversal
- C语言如何编写可变参数函数(涉及到二级指针)
- 使用RxJava来改进用户体验