Android-Context的IO功能,android-contextio
如何將應用資料儲存到本地檔案?如何從本地檔案載入資料到應用中?我實現的步驟是:
應用(java資料)<--org.json-->JSONString<--Context.IO-->本地檔案
今天向讀者講解的是Context.IO部分。
| File getDir(String name, int mode) |
擷取/data/data/<packagename>/目錄的子目錄(如不存在就先建立 它) |
| File getFilesDir() |
擷取/data/data/<packagename>/files目錄 |
| File getCacheDir() |
擷取/data/data/<packagename>/cache目錄。應注意及時清理該目錄,並節約使用空間
|
| String[] fileList() |
擷取/data/data/<packagename>/files目錄下的檔案清單。可與其他方 法配合使用,例如openFileInput(String) |
| FileInputStream openFileInput(String name) |
開啟現有檔案進行讀取 |
|
FileOutputStream openFileOutput(String name, int mode) |
開啟檔案進行寫入,如不存在就建立它 |
Context.IO實現本地檔案的字串輸入輸出
public class SerializerUtils { public static void save(Context c,String fileName,String data) throws IOException{ Writer writer=null; try{ OutputStream out=c.openFileOutput(fileName, Context.MODE_PRIVATE); writer=new OutputStreamWriter(out); writer.write(data); }finally{ if(writer!=null){ writer.close(); } } } public static String load(Context c,String fileName)throws IOException{ StringBuilder data=new StringBuilder(); BufferedReader reader=null; try{ InputStream in=c.openFileInput(fileName); reader=new BufferedReader(new InputStreamReader(in)); String line=null; while((line=reader.readLine())!=null){ data.append(line); } }finally{ if(reader!=null){ reader.close(); } } return data.toString(); }}