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

猜你喜欢

转载自blog.csdn.net/songzi1228/article/details/81871282