您的位置:首页 > 移动开发 > Android开发

Android文件的读取与保存

2015-11-04 20:07 357 查看
原理就是利用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: