標籤:android class blog code java http
背景
一些東西可以存在自己定義的檔案裡面,這個檔案可以在手機中,可以在SD卡中,在這裡就主要介紹一下在SD卡中的儲存和讀取吧~
代碼
public class save { public static void savefile2card(Context context,String username,String password) { File file = null; FileOutputStream fos = null; try { if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {// file = new File("/sdcard/info.txt"); file = new File(Environment.getExternalStorageDirectory(),"info.txt"); fos = new FileOutputStream(file); fos.write((username+"!!!!"+password).getBytes()); } else { Toast.makeText(context, "SD木有", Toast.LENGTH_LONG).show(); } } catch (Exception e) { // TODO 自動產生的 catch 塊 e.printStackTrace(); Toast.makeText(context, "Wrong", Toast.LENGTH_LONG).show(); try { fos.close(); } catch (IOException e1) { // TODO 自動產生的 catch 塊 e1.printStackTrace(); } }
}}
上面是存的代碼,這裡面用到了Environment.MEDIA_MOUNTED,查看是否掛載。
public class read { public static Map<String,String> getSaveFile(Context context) { //File file =new File(context.getFilesDir(),"info.txt"); File file = new File(Environment.getExternalStorageDirectory(),"info.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String str = br.readLine(); String[] infos = str.split("!!!!"); Map<String,String> map = new HashMap<String, String>(); map.put("username",infos[0]); map.put("password", infos[1]); br.close(); return map; } catch (Exception e) { // TODO 自動產生的 catch 塊 e.printStackTrace(); return null; } finally { } }}
上面是讀取的代碼,會存就會讀了,存得進去那麼就讀得出來撒~
原始碼:http://pan.baidu.com/s/1dD1Qx01
SDcard.zip