編輯:Android 開發教學
檔案是 Android 最基礎的持久化手段。本文依序說明安裝位置設定、內部儲存空間的讀寫、外部儲存空間的存取,以及 assets/raw/res 三個資源目錄的差異,最後附上一個 SD 卡檔案瀏覽器的實作。
Manifest 中 manifest 標籤下的 android:installLocation 屬性用於指定應用安裝位置,共三個可選值:
若要寫入外部儲存,需宣告權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Context 提供了兩個方法,直接開啟應用私有資料目錄下的檔案串流:
FileInputStream openFileInput(String name):取得指定檔案的輸入流。FileOutputStream openFileOutput(String name, int mode):取得輸出流,第二個參數為開啟模式:
存取私有資料目錄的輔助方法:
getDir(String name, int mode):取得或建立指定子目錄。getFileDir():取得資料目錄的絕對路徑。fileList():列出資料目錄下的所有檔案。deleteFile(String):刪除指定檔案。核心讀寫程式碼:
public String read() {
try {
FileInputStream inStream = this.openFileInput("message.txt");
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder();
while ((hasRead = inStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, hasRead));
}
inStream.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String msg) {
if (msg == null) return;
try {
// 以附加模式開啟,避免覆蓋既有內容
FileOutputStream fos = openFileOutput("message.txt", MODE_APPEND);
fos.write(msg.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
openFileOutput 的第一個參數只接受檔名,不可包含路徑分隔符「/」;檔案不存在時系統會自動建立,實際存放位置為 /data/data/<package name>/files/,例如 /data/data/cn.tony.app/files/message.txt。
標準流程有三步:
Environment.getExternalStorageState() 判斷外部儲存是否掛載且可讀寫,判斷條件為結果是否等於 Environment.MEDIA_MOUNTED。Environment.getExternalStorageDirectory() 取得外部儲存的根目錄。需宣告的權限:
<!-- 在 SD 卡中建立與刪除檔案 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 向 SD 卡寫入資料 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Environment 類別常用的靜態方法:
幾個實用工具方法:
/** 判斷外部儲存是否可用(無外掛卡時,內建 ROM 也可能被辨識為存在) */
public static boolean isSdCardExist() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/** 取得外部儲存根路徑 */
public static String getSdCardPath() {
if (isSdCardExist()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return "不適用";
}
/** 取得預設檔案路徑 */
public static String getDefaultFilePath() {
File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
return file.exists() ? file.getAbsolutePath() : "不適用";
}
讀取檔案的兩種常見寫法:
// 方式一:FileInputStream 一次讀完
try {
File file = new File(Environment.getExternalStorageDirectory(), "test.txt");
FileInputStream is = new FileInputStream(file);
byte[] b = new byte[is.available()];
is.read(b);
is.close();
System.out.println("讀取成功:" + new String(b));
} catch (Exception e) {
e.printStackTrace();
}
// 方式二:BufferedReader 逐行讀取
try {
File file = new File(Environment.getExternalStorageDirectory(), DEFAULT_FILENAME);
BufferedReader br = new BufferedReader(new FileReader(file));
String readline;
StringBuffer sb = new StringBuffer();
while ((readline = br.readLine()) != null) {
sb.append(readline);
}
br.close();
System.out.println("讀取成功:" + sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
完整的寫入與讀取範例(含目錄自動建立與錯誤提示):
// 寫入
private void write(String content) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "保存失敗,儲存卡不存在!", Toast.LENGTH_LONG).show();
return;
}
File file = new File(Environment.getExternalStorageDirectory().toString()
+ File.separator + DIR + File.separator + FILENAME);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); // 父目錄不存在則建立
}
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(file, true)); // 附加寫入
out.println(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) out.close();
}
}
// 讀取
private String read() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "讀取失敗,儲存卡不存在!", Toast.LENGTH_LONG).show();
return null;
}
File file = new File(Environment.getExternalStorageDirectory().toString()
+ File.separator + DIR + File.separator + FILENAME);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
Scanner scan = null;
StringBuilder sb = new StringBuilder();
try {
scan = new Scanner(new FileInputStream(file));
while (scan.hasNext()) {
sb.append(scan.next() + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scan != null) scan.close();
}
return null;
}
位於 main 之下、與 res 同層。與 res 最大的不同是:assets 下的檔案會以原始格式打包進 apk,不會被編譯或重新命名。三種常見用法:
// 以 WebView 載入 assets 中的 html
webView.loadUrl("file:///android_asset/test.html");
// 以串流讀取(open 只能開檔案,不能開目錄)
InputStream inputStream = getAssets().open("test.html");
// 列出子目錄內容
String[] fileNames = getAssets().list("images/");
// 讀取圖片
InputStream is = getAssets().open("images/dog.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bitmap);
// 讀取音訊
AssetFileDescriptor afd = getAssets().openFd("xuwei.mp3");
player.reset();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.prepare();
player.start();
位於 res 目錄下。系統會為 res 中的資源產生資源 ID,raw 中的檔案也不例外,因此可直接用 ID 存取;assets 則必須透過 AssetManager。另外,assets 允fielder有多層子目錄,res/raw 下不允許建立目錄結構。
InputStream is = getResources().openRawResource(R.raw.xuwei);
res 目錄下的檔案都可透過 getResources() 相關方法讀取。
利用 File 類別搭配 Environment.getExternalStorageDirectory() 取得根目錄,再以 listFiles() 取得該目錄下的檔案清單,就能做出一個簡易的瀏覽器。
主佈局 activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center_horizontal" />
<ListView android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/path" />
<Button android:id="@+id/parent"
android:layout_width="38dp"
android:layout_height="34dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/home" />
</RelativeLayout>
列表項佈局 line.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center_vertical">
<ImageView android:id="@+id/icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/folder"/>
<TextView android:id="@+id/file_name"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
主程式:
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private TextView mTextView;
private File mCurrentParent; // 當前所在目錄
private File[] mCurrentFiles; // 當前目錄下的檔案清單
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.list);
mTextView = (TextView) findViewById(R.id.path);
File root = new File(String.valueOf(Environment.getExternalStorageDirectory()));
if (root.exists()) {
mCurrentParent = root;
mCurrentFiles = root.listFiles();
inflateListView(mCurrentFiles);
}
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mCurrentFiles[position].isFile()) return; // 檔案不進入
File[] tmp = mCurrentFiles[position].listFiles();
if (tmp == null || tmp.length == 0) {
Toast.makeText(MainActivity.this, "當前路徑不可訪問或該路徑下沒有檔案",
Toast.LENGTH_SHORT).show();
} else {
mCurrentParent = mCurrentFiles[position];
mCurrentFiles = tmp;
inflateListView(mCurrentFiles);
}
}
});
// 返回上一層
Button parent = (Button) findViewById(R.id.parent);
parent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (!mCurrentParent.getCanonicalFile().equals("/mnt/shell/emulated/0")) {
mCurrentParent = mCurrentParent.getParentFile();
mCurrentFiles = mCurrentParent.listFiles();
inflateListView(mCurrentFiles);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void inflateListView(File[] files) {
List<Map<String, Object>> listItems = new ArrayList<>();
for (File file : files) {
Map<String, Object> listItem = new HashMap<>();
// 依檔案或目錄給不同圖示
listItem.put("icon", file.isDirectory() ? R.drawable.folder : R.drawable.file);
listItem.put("fileName", file.getName());
listItems.add(listItem);
}
SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.line,
new String[]{"icon", "fileName"},
new int[]{R.id.icon, R.id.file_name});
mListView.setAdapter(adapter);
try {
mTextView.setText("當前路徑為:" + mCurrentParent.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}

requestLegacyExternalStorage="true",但這只是過渡方案,targetSdk 30 以上已不受此旗標影響。getFilesDir()(私有內部)、getExternalFilesDir()(外部私有,免權限)或 MediaStore,而非直接拼接外部儲存路徑。
Android ListView 與 CheckBox 的資料綁定問題
在 ListView 中放入 CheckBox,常見需求是讓使用者勾選多個項目,最後再統一提交。若使用 SimpleAdapter,可透過 ViewBinder 把 Ma
給有 Java 基礎的初學者:Android 四大組件入門全解
過去一直是在論壇與部落格上「用到什麼查什麼」,從沒自己整理過。於是替自己立了個目標:把 Android 用到的技術點一條條寫下來,之後遇到類似問題能快速找到解法。這系列整
android中如何判斷edittext中資料為空
在 Android 中判斷 EditText 是否為空,常見錯誤是直接使用物件的 equals 方法。若字串本身為 null,呼叫 equals 可能觸發空指標異常。推薦
Eclipse 無法運行應用?揪出霸佔 adb 埠的幕後黑手
週一集團中高層的例會臨時取消,難得空出一段時間。先把上週擱置的幾件小事收尾,再繼續鑽研遊戲開發。打開 Eclipse 準備運行那個寫到一半的小範例,結果畫面直接跳出錯誤—