編輯:關於 Android 程式設計
程式處理完的資料要留到下次執行,就得靠儲存機制。Android 提供了五種主要方式:
這一課先把最基礎的「檔案」講透,後面幾課再逐一拆解其他方案。
順帶釐清一個常見誤解:許多人把 ROM 當成唯讀儲存,但這裡討論的儲存位置是應用可讀寫的資料區;真正用來放程式與唯讀資源的分割區,才是不能隨意寫入的。
Activity 直接提供了 openFileOutput(),用法與 J2SE 寫檔幾乎一致:
public class FileActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FileOutputStream outStream =
this.openFileOutput("itcast.txt", Context.MODE_PRIVATE);
outStream.write("趙雅智部落格".getBytes());
outStream.close();
}
}
只能給檔名,不能包含路徑分隔符「/」。檔案不存在時 Android 會自動建立。實際存放位置為:
/data/data/<package name>/files/
例如 /data/data/cn.itcast.action/files/itcast.txt。想確認檔案有沒有真的產生,可以在 Eclipse 中開啟「Window」→「Show View」→「Other」,展開 Android 資料夾選擇「File Explorer」,再展開上述目錄即可看到。
四種模式與對應的常數值:
Context.MODE_PRIVATE = 0 Context.MODE_APPEND = 32768 Context.MODE_WORLD_READABLE = 1 Context.MODE_WORLD_WRITEABLE = 2
MODE_PRIVATE:預設模式。檔案私有,僅應用本身可存取,寫入會覆蓋原內容。MODE_APPEND:檢查檔案是否存在,存在就追加內容,不存在則建立新檔。MODE_WORLD_READABLE:允許其他應用讀取此檔。MODE_WORLD_WRITEABLE:允許其他應用寫入此檔。若要同時開放讀與寫,把兩個常數相加:
openFileOutput("itcast.txt",
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Android 有一套自己的安全模型:應用程式(.apk)安裝時,系統會指派一個專屬的 user id;當應用要存取檔案等資源時,需要 user id 相符才放行。
因此,任何應用建立的檔案、SharedPreferences 與資料庫,預設都屬於私有(位於 /data/data/<package name>/files),其他程式無法存取。只有在建立時明確指定 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE,別人才讀得到。
FileInputStream inStream = this.getContext().openFileInput("itcast.txt");
Log.i("FileTest", readInStream(inStream));
把串流轉成字串的輔助方法:
public static String readInStream(FileInputStream inStream) {
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
}
outStream.close();
inStream.close();
return outStream.toString();
} catch (IOException e) {
Log.i("FileTest", e.getMessage());
}
return null;
}
也可以用絕對路徑直接開檔:
File file = new File("/data/data/cn.itcast.action/files/itcast.txt");
FileInputStream inStream = new FileInputStream(file);
Log.i("FileTest", readInStream(inStream));
注意路徑中的 cn.itcast.action 是應用所屬套件,實作時要換成自己程式的套件名。私有檔案只能由建立它的應用存取。
getCacheDir():取得 /data/data/<package name>/cache,適合放暫存檔,系統空間不足時可能會清除。getFilesDir():取得 /data/data/<package name>/files,適合放需要長期保留的檔案。<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.lession02_login"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lession02_login.LoginActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_name" />
<EditText
android:id="@+id/edit_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/view_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_pass" />
<EditText
android:id="@+id/edit_pass"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_login" />
<CheckBox
android:id="@+id/check_remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="@string/login_remember" />
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">lession02_login</string>
<string name="login_name">使用者名稱</string>
<string name="login_pass">密碼</string>
<string name="login_login">登入</string>
<string name="login_remember">記住密碼</string>
</resources>
package com.example.lession02_login.util;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
public class StreamTools {
public static String getValue(FileInputStream fis) throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer)) != -1) {
stream.write(buffer, 0, length);
}
stream.flush();
stream.close();
return stream.toString();
}
}
寫入時用 MODE_APPEND,這樣每次登入都會在檔案後方累加一筆;若改用 MODE_PRIVATE 則只會保留最後一筆。讀取時以冒號切分還原成 key-value。
package com.example.lession02_login.service;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import com.example.lession02_login.util.StreamTools;
import android.content.Context;
public class LoginService {
private Context context;
public LoginService(Context context) {
super();
this.context = context;
}
/**
* 把使用者名稱與密碼寫入應用私有檔案
*/
public boolean saveToRom(String name, String pass, String fileName) {
try {
// MODE_PRIVATE:僅應用本身可存取,內容會被覆蓋
// FileOutputStream fos = context.openFileOutput(
// fileName, Context.MODE_PRIVATE);
// MODE_APPEND:在既有內容後追加
FileOutputStream fos = context.openFileOutput(
fileName, Context.MODE_APPEND);
String result = name + ":" + pass;
fos.write(result.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 讀取檔案並還原為 Map
*/
public Map<String, String> readFile(String fileName) {
Map<String, String> map = null;
try {
FileInputStream fis = context.openFileInput(fileName);
String value = StreamTools.getValue(fis);
String values[] = value.split(":");
if (values.length > 0) {
map = new HashMap<String, String>();
map.put("name", values[0]);
map.put("pass", values[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
package com.example.lession02_login;
import java.util.Map;
import com.example.lession02_login.service.LoginService;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private EditText edit_name, edit_pass;
private Button btn_login;
private Checkable box_remember;
private LoginService loginService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginService = new LoginService(this);
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pass = (EditText) findViewById(R.id.edit_pass);
btn_login = (Button) findViewById(R.id.button_login);
box_remember = (Checkable) findViewById(R.id.check_remember);
btn_login.setOnClickListener(new MyOnclickListener());
// 回顯上次儲存的資料
Map<String, String> map = loginService.readFile("append.txt");
if (map != null) {
edit_name.setText(map.get("name"));
edit_pass.setText(map.get("pass"));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
class MyOnclickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_login:
String name = edit_name.getText().toString();
String pass = edit_pass.getText().toString();
if (TextUtils.isEmpty(name)) {
Toast.makeText(LoginActivity.this, "使用者名稱不可為空",
Toast.LENGTH_LONG).show();
return;
} else if (TextUtils.isEmpty(pass)) {
Toast.makeText(LoginActivity.this, "密碼不可為空",
Toast.LENGTH_LONG).show();
return;
}
if (box_remember.isChecked()) {
loginService.saveToRom(name, pass, "append.txt");
Toast.makeText(LoginActivity.this, "儲存使用者名稱與密碼",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "不儲存使用者名稱與密碼",
Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
}
}
在 File Explorer 或 shell 中看檔案,會看到類似 -rw-rw---- 的字串:
D 代表目錄,- 代表檔案。R 可讀、W 可寫、X 可執行。openFileOutput() 只收檔名,檔案固定落在 /data/data/<package name>/files/。MODE_PRIVATE 最安全;要累加用 MODE_APPEND;MODE_WORLD_* 兩個模式在後續版本已不建議使用。openFileInput(),搭配 ByteArrayOutputStream 緩衝區把串流轉字串。
Android Handler 實現執行緒間通訊:主執行緒與子執行緒的雙向溝通
在日常開發中,我們經常需要把背景執行緒的運算結果回傳給主執行緒(UI 執行緒)來更新介面。本文就來深入探討 Handler 的訊息傳遞機制,不只涵蓋子執行緒向主執行緒發送
天天看高清影視片庫無法連接的解決方案
天天看高清影視一直連不上片庫,試了很多次都一樣。以下把可能的原因整理成清單,你可以逐項對照,看能不能找到自己遇到的那一項。 天天看高清影視片庫無法連接的解決辦法: 1.
用 ListView 做時間軸:快遞物流軌跡頁的完整實作
實現思路 整個畫面以 ListView 為骨架,每個 ListItem 由兩個欄位構成:內容(content)與時間(time)。 時間軸的視覺部分並不是一張圖片,而是用
RxJava2 核心變化全解析
最近剛把 RxJava1.x 的源碼讀完,正好 RxJava2.x 也放出了 RC 版本。趁著正式版發布前的空檔,本文就來對 RxJava2.x 做一次入門級的剖析。