package com.fileop.demo.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
import android.os.Environment;
/**
* 业务类
* @author sky
*
*/
public class FileService {
private Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 以私有模式保存文件
* 会保存到 /data/data/应用程序包名/files/filename
* @param filename
* @param content
* @throws Exception
*/
public void save(String filename, String content) throws Exception {
/* Context.MODE_PRIVATE 为默认操作模式
Context.MODE_APPEND 也是私有数据,但可以追加文件
Context.MODE_WORLD_READABLE 表示当前文件可以被其他应用所读取
Context.MODE_WORLD_WRITEABLE 表示当前文件可以被其他应用所写入
如果希望文件被其他应用读和写,可传入
openFileOutput(filename, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
*/
FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 读取文件
* @param filename
* @return
* @throws Exception
*/
public String readFile(String filename) throws Exception{
FileInputStream inStream = context.openFileInput(filename);
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return new String(data);
}
/**
* 保存文件到SDCard中
* 在SDCard中穿件与删除文件权限:
* <uses-permission android:name="android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
* 向SDCard中写入数据权限:
* <uses-permission android:name="android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
* @param filename
* @param content
*/
public void saveToSDCard(String filename, String content) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(content.getBytes());
outStream.close();
}
/**
* 判断sdcard是否存在于手机上,并且没有写保护
* @return true 可用; false不可用
*/
public boolean isSDCardAvailable(){
if(Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
}