- // 向SD卡写入数据
- private void writeSDcard(String str) {
- try {
- // 判断是否存在SD卡
- if (Environment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED)) {
- // 获取SD卡的目录
- File sdDire = Environment.getExternalStorageDirectory();
- FileOutputStream outFileStream = new FileOutputStream(
- sdDire.getCanonicalPath() + "/test.txt");
- outFileStream.write(str.getBytes());
- outFileStream.close();
- Toast.makeText(this, "数据保存到text.txt文件了", Toast.LENGTH_LONG)
- .show();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 从SD卡中读取数据
- private void readSDcard() {
- StringBuffer strsBuffer = new StringBuffer();
- try {
- // 判断是否存在SD
- if (Environment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED)) {
- File file = new File(Environment.getExternalStorageDirectory()
- .getCanonicalPath() + "/test.txt");
- // 判断是否存在该文件
- if (file.exists()) {
- // 打开文件输入流
- FileInputStream fileR = new FileInputStream(file);
- BufferedReader reads = new BufferedReader(
- new InputStreamReader(fileR));
- String st = null;
- while ((st = reads.readLine()) != null) {
- strsBuffer.append(st);
- }
- fileR.close();
- } else {
- Toast.makeText(this, "该目录下文件不存在", Toast.LENGTH_LONG).show();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- Toast.makeText(this, "读取到的数据是:" + strsBuffer.toString() + "",
- Toast.LENGTH_LONG).show();
- }
- }
转载:http://blog.csdn.net/chaoyu168/article/details/50721480