首先如果要在程序中使用sdcard进行存储,我们必须要在AndroidManifset.xml文件进行下面的权限设置:
[html] view plain copy
-
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
-
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
接着在使用SDcard进行读写的时候 会用到Environment类下面的几个静态方法 :
1: getDataDirectory() 获取到Android中的data数据目录(sd卡中的data文件夹)
2:getDownloadCacheDirectory() 获取到下载的缓存目录(sd卡中的download文件夹)
3:getExternalStorageDirectory() 获取到外部存储的目录 一般指SDcard(/storage/sdcard0)
4:getExternalStorageState() 获取外部设置的当前状态 一般指SDcard,比较常用的应该是 MEDIA_MOUNTED(SDcard存在并且可以进行读写)还有其他的一些状态,可以在文档中进行查找。
5:getRootDirectory() 获取到Android Root路径
好,以下是具体操作,直接看代码:
1,判断SD卡是否存在
[java] view plain copy
-
-
-
-
-
- public static boolean isSdCardExist() {
- return Environment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED);
- }
2,获取SD卡根目录
[java] view plain copy
-
-
-
-
-
- public static String getSdCardPath() {
- boolean exist = isSdCardExist();
- String sdpath = "";
- if (exist) {
- sdpath = Environment.getExternalStorageDirectory()
- .getAbsolutePath();
- } else {
- sdpath = "不适用";
- }
- return sdpath;
-
- }
3,获取默认的文件存放路径
[java] view plain copy
-
-
-
-
-
- public static String getDefaultFilePath() {
- String filepath = "";
- File file = new File(Environment.getExternalStorageDirectory(),
- "abc.txt");
- if (file.exists()) {
- filepath = file.getAbsolutePath();
- } else {
- filepath = "不适用";
- }
- return filepath;
- }
4-1,使用FileInputStream读取文件
[java] view plain copy
- try {
- le file = new File(Environment.getExternalStorageDirectory(),
- "test.txt");
- FileInputStream is = new FileInputStream(file);
- byte[] b = new byte[inputStream.available()];
- is.read(b);
- String result = new String(b);
- System.out.println("读取成功:"+result);
- } catch (Exception e) {
- e.printStackTrace();
- }
4-2,使用BufferReader读取文件
[java] view plain copy
- try {
- File file = new File(Environment.getExternalStorageDirectory(),
- DEFAULT_FILENAME);
- BufferedReader br = new BufferedReader(new FileReader(file));
- String readline = "";
- StringBuffer sb = new StringBuffer();
- while ((readline = br.readLine()) != null) {
- System.out.println("readline:" + readline);
- sb.append(readline);
- }
- br.close();
- System.out.println("读取成功:" + sb.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
httpConnection读取流保存成String数据
[java] view plain copy
- URL url = new URL(getForwardUrl("/queryUserByUNorIP"));
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- InputStream is = conn.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- StringBuilder sb = new StringBuilder();
-
String readline = null; <li class="alt" style="border-top: none; border-right: none;%