import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;
public class FileService {
private Context context;
public FileService(Context context) {
super();
this.context = context;
}
/**
* 保存文件到系统存储中
* @param title 文件名
* @param content 文件内容
* @param model 文件存储模式
* context.MODE_APPEND;------------私有追加模式
context.MODE_PRIVATE;-----------私有覆蓋模式
context.MODE_WORLD_READABLE;----外部可讀
context.MODE_WORLD_WRITEABLE;---外部可写
* @throws Exception
*/
public void save(String title,String content,Integer mode) throws Exception{
FileOutputStream fileOutputStream = context.openFileOutput(title, mode);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
/**
* 读取项目内部指定文件
* @param title
* @return
* @throws Exception
*/
public String read(String title) throws Exception{
FileInputStream fileInputStream = context.openFileInput(title);
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while((len = fileInputStream.read(bytes)) != -1){
arrayOutputStream.write(bytes, 0, len);
}
byte[] data = arrayOutputStream.toByteArray();
return new String(data);
}
/**
* 保存到sdcard上
* Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)判断是否可用SD卡
* @param title
* @param content
* @throws Exception
*/
public void saveToSD(String title,String content) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(), title);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
}