經典的流操做java
openFileOutput()sql
public void save() { String data = "Data to save"; FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(data); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } }
自動保存到 /data/data/<項目id>/files/數據庫
openFileInput()安全
public String load() { FileInputStream in = null; BufferedReader reader = null; StringBuilder content = new StringBuilder(); try { in = openFileInput("data"); reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { content.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return content.toString(); }
鍵值對形式存儲,xml形式格式。app
getSharedPreferences(文件名,模式)ide
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit(); editor.putString("name", "Tom"); editor.putInt("age", 28); editor.putBoolean("married", false); editor.commit();
存地址 /data/data/<項目id>/shared_prefs /學習
SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE); String name = pref.getString("name", ""); int age = pref.getInt("age", 0); boolean married = pref.getBoolean("married", false);
###SQLite 數據庫存儲 你懂的。ui
public class MyDatabaseHelper extends SQLiteOpenHelper { //接收參數:String name, 數據庫名稱 int version 用於更新版本 public MyDatabaseHelper(Context context, String name, CursorFactoryfactory, int version){} @Override public void onCreate(SQLiteDatabase db) { db.execSQL(sql語句); } //只有在version 變大時才執行 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1); //這一步就建立數據庫,和表結構了 SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", "The Da Vinci Code"); values.put("author", "Dan Brown"); // C db.insert("Book", null, values); // U db.update("Book", values, "name = ?", new String[] { "Tom" }); // D db.delete("Book", "name = ?", new String[] { "Tom" }); // R //String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) Cursor cursor = db.query("Book", null, null, null, null, null, null); while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex("name")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); } cursor.close();
固然你也能夠本身寫sqlthis
db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)", new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" })
db.beginTransaction(); // 開啓事務code
db.setTransactionSuccessful(); // 事務已經執行成功
db.endTransaction(); // 結束事務
內容提供器( Content Provider) 下文學習