編輯:關於 Android 程式設計
把資料落地到外部儲存空間,是許多 App 的基本需求。本文以最單純的 txt 文字檔為例,走一遍完整流程:權限宣告、封裝讀寫工具類、寫測試用的 UI,最後實際跑起來看結果。
操作外部儲存空間前,必須先取得權限,否則會在執行期直接拋出 SecurityException。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.tes.textsd"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.tes.textsd.FileOperateActivity"
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>
這裡刻意沒有把 MainActivity 當成程式入口,而是直接指定 FileOperateActivity。
把檔案操作集中到一個工具類裡,後續要換成資料庫或雲端儲存時也好替換。
package com.tes.textsd;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
public class FileHelper {
private Context context;
/** SD 卡是否存在 **/
private boolean hasSD = false;
/** SD 卡的路徑 **/
private String SDPATH;
/** 當前程式包的路徑 **/
private String FILESPATH;
public FileHelper(Context context) {
this.context = context;
hasSD = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
SDPATH = Environment.getExternalStorageDirectory().getPath();
FILESPATH = this.context.getFilesDir().getPath();
}
/**
* 在 SD 卡上創建檔案
* @throws IOException
*/
public File createSDFile(String fileName) throws IOException {
File file = new File(SDPATH + "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
return file;
}
/**
* 刪除 SD 卡上的檔案
* @param fileName
*/
public boolean deleteSDFile(String fileName) {
File file = new File(SDPATH + "//" + fileName);
if (file == null || !file.exists() || file.isDirectory())
return false;
return file.delete();
}
/**
* 寫入內容到 SD 卡中的 txt 文字檔
* @param str 為內容
*/
public void writeSDFile(String str, String fileName) {
try {
FileWriter fw = new FileWriter(SDPATH + "//" + fileName);
File f = new File(SDPATH + "//" + fileName);
fw.write(str);
FileOutputStream os = new FileOutputStream(f);
DataOutputStream out = new DataOutputStream(os);
out.writeShort(2);
out.writeUTF("");
System.out.println(out);
fw.flush();
fw.close();
System.out.println(fw);
} catch (Exception e) {
}
}
/**
* 讀取 SD 卡中的文字檔
* @param fileName
* @return
*/
public String readSDFile(String fileName) {
StringBuffer sb = new StringBuffer();
File file = new File(SDPATH + "//" + fileName);
try {
FileInputStream fis = new FileInputStream(file);
int c;
while ((c = fis.read()) != -1) {
sb.append((char) c);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public String getFILESPATH() {
return FILESPATH;
}
public String getSDPATH() {
return SDPATH;
}
public boolean hasSD() {
return hasSD;
}
}
建構子裡的三行是重點:用 Environment.getExternalStorageState() 判斷卡是否掛載,用 getExternalStorageDirectory() 取外部儲存根路徑,用 getFilesDir() 取 App 私有目錄。
用幾個 TextView 把各項狀態顯示出來,一眼就能看出每一步的結果。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/hasSDTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<TextView
android:id="@+id/SDPathTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<TextView
android:id="@+id/FILESpathTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<TextView
android:id="@+id/createFileTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="false" />
<TextView
android:id="@+id/readFileTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="false" />
<TextView
android:id="@+id/deleteFileTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="false" />
</LinearLayout>
package com.tes.textsd;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class FileOperateActivity extends Activity {
private TextView hasSDTextView;
private TextView SDPathTextView;
private TextView FILESpathTextView;
private TextView createFileTextView;
private TextView readFileTextView;
private TextView deleteFileTextView;
private FileHelper helper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hasSDTextView = (TextView) findViewById(R.id.hasSDTextView);
SDPathTextView = (TextView) findViewById(R.id.SDPathTextView);
FILESpathTextView = (TextView) findViewById(R.id.FILESpathTextView);
createFileTextView = (TextView) findViewById(R.id.createFileTextView);
readFileTextView = (TextView) findViewById(R.id.readFileTextView);
deleteFileTextView = (TextView) findViewById(R.id.deleteFileTextView);
helper = new FileHelper(getApplicationContext());
hasSDTextView.setText("SD 卡是否存在:" + helper.hasSD());
SDPathTextView.setText("SD 卡路徑:" + helper.getSDPATH());
FILESpathTextView.setText("包路徑:" + helper.getFILESPATH());
try {
createFileTextView.setText("創建檔案:"
+ helper.createSDFile("test.txt").getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
deleteFileTextView.setText("刪除檔案是否成功:"
+ helper.deleteSDFile("xx.txt"));
helper.writeSDFile("1213212", "test.txt");
readFileTextView.setText("讀取檔案:" + helper.readSDFile("test.txt"));
}
}
執行結果如下:

第一,Android 4.4(API 19)之後,WRITE_EXTERNAL_STORAGE 只能保證寫入 App 專屬目錄;要寫到公共目錄,建議改用 getExternalFilesDir() 或 MediaStore API,並在 Android 6.0 以上處理執行期權限請求。
第二,範例中的 writeSDFile 同時用了 FileWriter 和 DataOutputStream 寫同一個檔案,實務上應該只保留一種寫入方式,避免互相干擾。另外 catch (Exception e) {} 這種空字串捕捉是絕對要避免的寫法,至少該把例外訊息印出來,否則出問題時完全無從查起。
第三,檔案讀寫屬於 I/O 操作,放在 onCreate 也就是主執行緒上會造成畫面卡頓,正式專案請務必移到背景執行緒。
Android Zxing 二維碼掃描畫面被拉伸的解決方法
使用 Zxing 做二維碼掃描時,若把預設的橫屏改成豎屏,掃描畫面往往會出現變形拉伸的狀況。Zxing 是 Google 提供的二維碼掃描開源專案,這個問題可以透過修改原
讓 select2 搜尋框支援拼音輸入:改寫 matcher 並掛上拼音對照表
select2 的下拉搜尋預設只比對選項文字本身,中文選項 therefore 只能打中文字才有反應。對使用者來說很不友善——誰會記得每個選項的完整用字?只要加一層拼音映
Android 音樂播放器實作(二十):下載完成後通知主界面刷新本地音樂列表
本篇要解決的問題:歌曲下載完成之後,主界面要能自動更新本地音樂列表。 除了下面要講的這個環節,專案裡還有一些待修的 BUG,後續文章會持續補充。 一、問題與解法 下載完
PUSCH 上行跳頻(二):Type2 子帶跳頻原理全解析
一、採用 PUSCH 跳頻時必須留意的細節 在一個上行子幀裡,PUCCH 信道通常分佈在帶寬的兩端,也就是頻譜的邊緣位置;而 PUSCH 信道則集中於帶寬的中間區域。無論