android 一般读写文件的方法。
来源:互联网 发布:数据库开发工程师任务 编辑:程序博客网 时间:2024/05/21 12:43
android 读写文件操作,虽然很简单,但是有时候会忘记,先记下来:
读写文件一般用于读写缓存,因为数据库听说存储的字符串长度是有限的。
要注意的地方:
1.操作之前要先添加相关权限
2.mkdir()方法和mkdirs()方法的区别在于mkdir()方法只能创建一层目录,如果要创建像 “c://aa/bb/dd” 这样多层目录的就要用mkdirs()方法.
写文件的一个例子:
/** * 将信息写入文件缓存 */ public void writeCacheToFile(String dataString, String cacheFileName) { boolean flag = false; FileOutputStream fileOutputStream = null; try { //文件存储目录 String tempPath = Environment.getExternalStorageDirectory().getPath() + "/rrlTemp/Cache"; File file = new File(tempPath); if (!file.exists()) { file.mkdirs(); } File f = new File(tempPath, cacheFileName + ".txt"); //判断SD卡是否可用 if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { fileOutputStream = new FileOutputStream(f); byte[] bytes = dataString.getBytes(); fileOutputStream.write(bytes); flag = true; } else { //没内存卡就存机身内存 f = new File("data/data/com.lzx.rrl/" + cacheFileName + ".txt"); } if (!f.exists()) { f.createNewFile(); } } catch (Exception e) { L.i("写文件==" + e.toString()); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (Exception e) { L.i("关闭流==" + e.toString()); } } } }
读文件的一个例子:
/** * 读文件缓存 */ public String readCacheToFile(String cacheFileName) throws UnsupportedEncodingException { FileInputStream inputStream = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //文件路径 String tempPath = Environment.getExternalStorageDirectory().getPath() + "/rrlTemp/Cache"; File file = new File(tempPath, cacheFileName + ".txt"); 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 (Exception e) { L.i("读文件=" + e.toString()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { L.i("关闭流==" + e.toString()); } } } } else { file = new File("data/data/com.lzx.rrl/" + cacheFileName + ".txt"); } return new String(outputStream.toByteArray(), "UTF-8"); }
0 0
- android 一般读写文件的方法。
- Android SharedPreferences一般的读写
- Android SharedPreferences一般的读写
- 【Android读写文件方法汇总】
- Android 读写文件方法汇总
- Android文件的读写
- Android文件的读写
- Android文件的读写
- Android的文件读写
- Android文件的读写
- Android 文件的读写
- Android文件的读写
- c# 读写文本文件(一般用于日志文件的编程)
- 在android开发中正确读写sdcard文件的方法
- Android开发中正确读写sdcard文件的方法
- 读写ini文件的方法
- ini文件的读写方法
- 大文件的读写方法
- Mac OS apache php配置
- CSS选择器
- Leaving on a jet plane
- oracle中默认的编码格式
- ubuntu mysql远程连接
- android 一般读写文件的方法。
- IOS吐槽狂人:三原色
- CentOS 6.5下搭建hadoop 2.6.0集群(一):安装配置JDK
- 欢迎使用CSDN-markdown编辑器
- python练习2
- 欢迎使用CSDN-markdown编辑器
- UIScrollView, UIPageControl 的详细使用
- 一个自己用lucene写的敏感词查询
- 抽奖算法