標籤:android 檔案
檔案的儲存
public static boolean saveUserInfo(Context context, String username, String password){try{// 定義一個檔案路徑對象File file = new File(context.getFilesDir(), "info.txt");// 定義一個檔案的寫入流對象FileOutputStream fos = new FileOutputStream(file);// 用檔案的寫入流對象寫資料到檔案裡面fos.write((username + "##" + password).getBytes());// 關閉檔案的寫入流fos.close();return true;}catch (Exception e){e.printStackTrace();return false;}}
檔案的讀取
public static Map<String, String> getSavedUserInfo(Context context){try{// 定義一個檔案路徑對象File file = new File(context.getFilesDir(), "info.txt");// 定義一個檔案的讀取流對象fisFileInputStream fis = new FileInputStream(file);// 定義一字元的讀取流對象brBufferedReader br = new BufferedReader(new InputStreamReader(fis));// 讀取文字檔中的一行資料String string = br.readLine();// 使用split方法風格字串,將分割之後的字串資料儲存到字串數組裡面String[] infos = string.split("##");// 定義一個Map集合,用來儲存分割的字串數組資訊Map<String, String> map = new HashMap<String, String>();map.put("username", infos[0]);map.put("password", infos[1]);return map;}catch (Exception e){e.printStackTrace();return null;}}