Android平台下的數據存儲主要包括文件的流讀取,輕量級數據庫SQLite,ContentProvider和Preference
當App被安裝後.其所在的安裝包中會有一個相應的文件夾用於存放自己的數據.只有應用程序自己本身才對這個文件夾有寫入權限,路徑是/data/data/APP包名/.下面是使用文件I/O方法直接往手機中存儲數據.主要使用了FileInputStream和FileOutputStream這個兩個類.
- public class UIDataActivity extends Activity {
-
- public static final String ENCODING = "UTF-8";
- String fileName="test.txt";
- String message = "Android數據存儲I/O例子 ";
- TextView textView;
-
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- /*
- * 本示例是應用程序在私有數據文件夾下創建一個文件並讀取其中的數據顯示在TextView上
- */
-
- writeFileData(fileName,message);
-
- String result = readFileData(fileName);
-
- textView = (TextView)findViewById(R.id.tv);
- textView.setText(result);
- }
-
- public void writeFileData(String fileName,String message){
- //使用FileOutputStream對象如果文件不存在或者不可以寫入時.會拋出FileNotFoundException異常
- try {
- FileOutputStream stream = openFileOutput(fileName, MODE_PRIVATE);
- byte[] bytes = message.getBytes();
- stream.write(bytes);
- stream.close();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- public String readFileData(String fileName){
- String result ="";
- try {
- FileInputStream stream = openFileInput(fileName);
- int len = stream.available();
- byte[] bytes = new byte[len];
- stream.read(bytes);
- result = EncodingUtils.getString(bytes, ENCODING);
- stream.close();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- }