編輯:關於 Android 開發
資料儲存的方式有好幾種,檔案是最基礎的一種。這一課分兩個部分:把資料寫進手機內部儲存空間,以及寫進 SD 卡。兩者的 API 相似,但權限與路徑取得方式不同,實作時要分清楚。
實作步驟:先建立布局檔(包含檔名與內容輸入框);在主 Activity 中取得控件並為按鈕掛上監聽器,負責讀取輸入內容並觸發儲存;由於業務邏輯通常放在 service 層,因此另外建立業務類別來完成寫入。
public class MainActivity extends Activity implements OnClickListener {
private Button mButton;
private EditText etFilename;
private EditText etFileContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
etFilename = (EditText) findViewById(R.id.filename);
etFileContent = (EditText) findViewById(R.id.filecontent);
String filename = etFilename.getText().toString();
String filecontent = etFileContent.getText().toString();
FileService service = new FileService(getApplicationContext());
try {
service.save(filename, filecontent);
Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
public class FileService {
private Context context;
public FileService(Context context) {
this.context = context;
}
/** 儲存檔案到手機內部儲存 */
public void save(String filename, String filecontent) throws Exception {
/**
* FileOutputStream:檔案輸出流
* openFileOutput() 的參數:
* 1. 要儲存的檔案名稱
* 2. 儲存模式
* 這裡使用 MODE_PRIVATE,代表產生的檔案只能被本應用存取,
* 且寫入時會覆蓋原檔案的內容。
*/
FileOutputStream outputStream =
context.openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(filecontent.getBytes());
outputStream.close();
}
/** 從手機內部儲存讀取檔案 */
public String read(String filename) throws Exception {
FileInputStream inputStream = context.openFileInput(filename);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
byte[] data = outputStream.toByteArray();
return new String(data);
}
}
除了 MODE_PRIVATE,另外兩個常用模式是 MODE_APPEND(追加而不覆蓋)與 MODE_WORLD_READABLE/MODE_WORLD_WRITEABLE(對外開放讀寫)。後兩者在 API 17 之後已被標記為危險並在後續版本停用,實務上不該再使用;需要對外分享檔案時,應改用 FileProvider。
public class FileServiceTest extends AndroidTestCase {
private static final String TAG = "FileServiceTest";
/** 測試 save() 方法是否有錯 */
public void testSave() throws Throwable {
FileService service = new FileService(this.getContext());
service.save("456.txt", "sdfdgsdfasd");
Log.i(TAG, "成功");
}
/** 測試 read() 方法是否有錯 */
public void testRead() throws Throwable {
FileService service = new FileService(this.getContext());
String result = service.read("123.txt");
Log.i(TAG, result);
}
}
要執行單元測試,必須在清單檔中加上 instrumentation 標籤與 uses-library:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.rookie.test1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<!-- 指定單元測試的唯一標識 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.rookie.test1"
android:label="testapp"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- 加入單元測試環境 -->
<uses-library android:name="android.test.runner" />
<activity
android:name=".MainActivity"
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>
⑤ 布局檔 activity_main.xml(此處省略)
要寫入 SD 卡,必須先在清單檔中宣告相關權限:
<!-- 在 sd 卡中建立與刪存檔案的權限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 往 sd 卡寫入資料的權限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
接著在 FileService.java 中新增一個方法:
/** 儲存檔案到 sdcard */
public void saveToSDCard(String filename, String filecontent) throws Exception {
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(filecontent.getBytes());
outputStream.close();
}
然後把 MainActivity 中原本改寫過的 onClick() 改成:
@Override
public void onClick(View v) {
etFilename = (EditText) findViewById(R.id.filename);
etFileContent = (EditText) findViewById(R.id.filecontent);
String filename = etFilename.getText().toString();
String filecontent = etFileContent.getText().toString();
FileService service = new FileService(getApplicationContext());
try {
// 先判斷 sd 卡是否存在且可讀寫
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
service.saveToSDCard(filename, filecontent);
Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.sd_error, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
到這裡,寫入 SD 卡的功能就完成了,跑一下試試看。
openFileOutput() 存的那片空間叫「內部儲存」,而把一般使用者認知的 SD 卡叫「外部儲存」。兩者都不需要 SD 卡權限前者需要,後者需要 WRITE_EXTERNAL_STORAGE。requestPermissions() 向使用者取得同意,否則會直接收到 SecurityException。try (FileOutputStream os = ...) 自動關閉。
Android 入門學習筆記:手把手打造你的第一個安卓程式
本文記錄了從零開始搭建 Android 開發環境、建立第一個 App 的完整流程,適合剛接觸安卓開發的新手照著一步步實作。 一、安裝 JDK 並配置系統環境變數 JDK
重新思考 Android Activity 設計:從常見抱怨到優化方向
Activity 設計帶來的開發痛點 Android 的 Activity 設計強調執行期獨立性。每個 Activity 都必須在 AndroidManifest.xml
解決 JNI 開發中 java 頭文件 unresolved inclusion 報錯
在 Eclipse 下搭建好 NDK 開發環境後,打開 samples 裡的 hello-jni 項目,添加 native 支持和運行都很正常,可一旦打開 hello-j
Android 簡訊還原:用 ContentResolver 寫回一筆訊息
Android 簡訊還原:用 ContentResolver 寫回一筆訊息 上一篇〈Android 簡訊的備份〉談的是把訊息讀出來存到檔案;這次要處理反向操作——把一筆訊