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
原创粉丝点击