public class FileService
{
private Context context;
public FileService(Context context)
{
this.context = context;
}
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();
}
/**
* 儲存檔案
*
* @param filename
* 檔案名稱
* @param content
* 檔案內容
*/
public void save(String filename, String content) throws Exception
{
// 私人操作模式:建立出來的檔案只能被本應用訪問,其它應用無法訪問該檔案,另外採用私人操作模式建立的檔案,寫入檔案中的內容會覆蓋原檔案的內容
FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);//預設的模式,檔案為私人模式只能被自身訪問,寫入的檔案會覆蓋原有的檔案。
outStream.write(content.getBytes());
outStream.close();
}
檔案儲存的幾種模式
Context.MODE_PRIVATE);//預設的模式,檔案為私人模式只能被自身訪問,寫入的檔案會覆蓋原有的檔案。
Context.MODE_APPEND;//模式檢查是否檔案是否存在,若存在就往檔案裡面追加內容,否則就建立新檔案
Context.MODE_WORLD_READABLE;//表示當前檔案可以被其他應用讀取
Context.MODE_WORLD_WRITEABLE;//表示當前檔案被其他應用寫入
/**
* 讀取檔案內容
*
* @param filename
* 檔案名稱
* @return 檔案內容
* @throws Exception
*/
public String read(String filename) throws Exception
{
FileInputStream inStream = context.openFileInput(filename);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];// 設定讀取位元組數組的大小
int len = 0;
while ((len = inStream.read(buffer)) != -1)
{// 判斷是否讀取完的方法
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();// 輸出
return new String(data);
}
}