【Android数据存储】文件存取的方法

1、存储方法:

/**
     * 把字符串数据写入文件
     *
     * @param content 需要写入的字符串
     * @param path    文件路径名称
     * @param append  是否以添加的模式写入
     * @return 是否写入成功
     */
    public static boolean writeFile(byte[] content, String path, boolean append) {
        boolean res = false;
        File f = new File(path);
        RandomAccessFile raf = null;
        try {
            if (f.exists()) {
                if (!append) {
                    f.delete();
                    f.createNewFile();
                }
            } else {
                f.createNewFile();
            }
            if (f.canWrite()) {
                raf = new RandomAccessFile(f, "rw");
                raf.seek(raf.length());
                raf.write(content);
                res = true;
            }
        } catch (Exception e) {
            HnLogUtils.e("Err", e.toString());
        } finally {
            IOUtils.close(raf);
        }
        return res;
    }

2、读取方法:


    public static String readFileList(File filePath) {
        FileReader fir = null;
        BufferedReader bufr = null;
        String data = null;
        try {
            if (!filePath.exists() || !filePath.isFile()) {
                filePath.createNewFile();
            }
            fir = new FileReader(filePath);
            bufr = new BufferedReader(fir);
            data = bufr.readLine();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

3、存储路径的获取

String path = mContext.getFilesDir().getAbsolutePath();

path = path + File.separator + directoryName + File.separator + fileName;

directoryName:chat

fileName : hearder.png

得到的path即为: ///data/user/0/com.my.company/files/chat/hearder.png

 

参考文章:

Android 保存文件路径方法 

https://www.jb51.net/article/144924.htm

android数据存储之文件存储方法 

https://www.jb51.net/article/97374.htm

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值