筆記如下
- 保存數據到應用私有的目錄中并回顯
//相當于/data/data/com...../info.txt
File file = new File(this.getFilesDir(),"info.txt");
OutputStream out = new FileOutputStream(file);
String value = number+"#itheima#"+password;
out.write(value.getBytes());
out.close();
數據回顯
File file = new File(this.getFilesDir(),"info.txt");
// /data/data/com......./cache
// File file = new File(this.getCacheDir(),"info.txt");
if(file.exists()&&file.length()>0){
// 讀取 file 中數據 , 然后回顯
try {
BufferedReader br = new BufferedReader(new FileReader(file));
// 111#itheima#111
String line = br.readLine();
String num= line.split("#itheima#")[0];
String pwd = line.split("#itheima#")[1];
ed_qqnumber.setText(num);
ed_qqpassword.setText(pwd);
} catch (Exception e) {
e.printStackTrace();
}
}
- 將數據保存到公共sdk卡上
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
// 判斷sdcar的 狀態
String status = Environment.getExternalStorageState();
// 這里 status 動態的返回的 sd 卡的狀態
// 如果是mouted --- 掛載 , 那么這個時候 可以去 寫 數據到 sd 卡中
if(!Environment.MEDIA_MOUNTED.equals(status)){
// 表示 sd 卡 未 掛載, 那么 這個時候 就提示用戶 檢查sd 卡的狀態
Toast.makeText(this, "請檢查 sd 卡的狀態 ", 0).show();
return;
}
// 細節二 :
// 返回可用的 空閑的 空間 大小 ---- in bytes
long freeSpace = Environment.getExternalStorageDirectory().getFreeSpace();
//拿到 sd 卡的總的大小, in bytes
Environment.getExternalStorageDirectory().getTotalSpace();
//拿到 sd 卡 已經使用的 的大小, in bytes
Environment.getExternalStorageDirectory().getUsableSpace();
// 調用這個api 去獲得sd 卡的 可用 控件, 這里還做了一個事, 將 返回的字節 空間 做了單位的
// 轉換
String avalableSize = Formatter.formatFileSize(this, freeSpace);
Toast.makeText(this,"可用的 空間 是 : "+ avalableSize, 0).show();
File file = new File(Environment.getExternalStorageDirectory(),"info.txt");
OutputStream out = new FileOutputStream(file);
String value = number+"#"+password;
out.write(value.getBytes());
out.close();
- 用sharedPreference保存數據
// 將數據 保存起來, 使用 sharedPreference
// config文件將會生成 在 應用的文件夾下 --- 一個 xml 格式 的文件
// 一般 情況下, 應用自己的數據 只有 當前應用 自己可以去讀, 所以 通常 會寫
sp = getSharedPreferences("config", 0);
Editor editor = sp.edit();
editor.putString("number", number);
editor.putString("password", password);
editor.commit();
回顯數據
sp = getSharedPreferences("config", 0);
// 如果找到了 number的 值, 那么 就 返回 number的值, 否則 就返回 這里的默認值
String num= sp.getString("number", "");
String pwd= sp.getString("password", "");