当前位置:首页 > 移动开发 > 正文

Android_内部存储文件的读写

2024-03-31 移动开发

内部存储文件即raw和assets项目文件夹下的文件,项目卸载时被删除。

四种文件操作模式 

 

 

文件存储: 

public void save(String filename, String filecontent) throws Exception {

        //这里我们使用私有模式,创建出来的文件只能被本应用访问,还会覆盖原文件

        FileOutputStream output = mContext.openFileOutput(filename, Context.MODE_PRIVATE);

        output.write(filecontent.getBytes());  //将String字符串以字节流的形式写入到输出流中

        output.close();         //关闭输出流

}

 

文件读取:

 public String read(String filename) throws IOException {

        //打开文件输入流

        FileInputStream input = mContext.openFileInput(filename);

        byte[] temp = new byte[1024];

        StringBuilder sb = new StringBuilder("");

        int len = 0;

        //读取文件内容:

        while ((len = input.read(temp)) > 0) {

            sb.append(new String(temp, 0, len));

        }

        //关闭输入流

        input.close();

        return sb.toString();

    }

 

 

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/yidong/10968.html