Android文件的读取与保存

来源:互联网 发布:第三方软件问题 编辑:程序博客网 时间:2024/05/27 20:55

原理就是利用java的IO。

openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 会自动创建它。创建的文件保存在/data/data/<packagename>/files目录。

可以通过File Explorer查看。点击右上角的可以导出到电脑里。

openFileOutput()方法的第二参数用于指定操作模式

私有操作模式创建出来的文件只能被本应用所访问,其他应用无法方法该文件,另外采用私有操作模式创建的文件,写入文件中的内容会覆盖原文件的内容

package com.example.service;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import android.content.Context;public class FileService {private Context context;public FileService(Context context) {super();this.context = context;}/** * 保存文件 * @param filename 文件名称 * @param filecontent 文件内容 * @throws Exception  */public void save(String filename, String filecontent) throws Exception {FileOutputStream outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);outputStream.write(filecontent.getBytes());outputStream.close();}/** * 读取文件内容 * @param fileName 文件名称 * @return 文件内容 * @throws Exception */public String read(String fileName) throws Exception{FileInputStream instream  = context.openFileInput(fileName);ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while((len = instream.read(buffer)) != -1){outputStream.write(buffer,0,len);}byte []data = outputStream.toByteArray();return new String(data);}}
通过FileInputStream读取了文件之后,要通过FileInputStream的read方法,把信息读到数组中去,然后再通过ByteArrayputStream把数组中的东西读到内存中去。

转载地址http://blog.csdn.net/howlaa/article/details/17285521

0 0