SD Card 读写
对sdcrad 进行读写与普通java IO一样,只需要在使用前使用 Environment.getExternalStorageState() 判断sdcard 是否可用
Android Data Storage
常用的几种存储方式
- SharedPreferences
- External Storage
- SQLite
SD Card 属于 External Storage
通过添加下面的权限才可以使用
1 2 3 4
| <manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public String getFileFromSdcard(String fileName) { FileInputStream inputStream = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); File file = new File(Environment.getExternalStorageDirectory(), fileName); if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { try { inputStream = new FileInputStream(file); int len = 0; byte[] data = new byte[1024]; while ((len = inputStream.read(data)) != -1) { outputStream.write(data, 0, len); }
} catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
}
return new String(outputStream.toByteArray()); }
/** * @param fileName * 文件的名称 * @param content * 文件的内容 * @return */ public boolean saveContentToSdcard(String fileName, String content) { boolean flag = false; FileOutputStream fileOutputStream = null; File file = new File(Environment.getExternalStorageDirectory(), fileName); if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { try { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(content.getBytes()); flag = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } return flag; }
|
Posted by scalaview - 2014-06-09
如需转载,请注明: 本文来自 王见充时光