在 Android 中,使用 FileChooser 可以讓用戶從設備中選擇文件
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static final int FILE_PICK_REQUEST_CODE = 1;
private void openFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
try {
startActivityForResult(
Intent.createChooser(intent, "選擇文件"),
FILE_PICK_REQUEST_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "請安裝文件管理器", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICK_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
if (uri != null) {
// 在這里處理所選文件的 Uri,例如獲取文件名和讀取內容等
String fileName = getFileNameFromUri(this, uri);
// ...
}
}
}
public String getFileNameFromUri(Context context, Uri uri) {
String fileName = "";
if (uri.getScheme().equalsIgnoreCase("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (fileName.isEmpty()) {
fileName = uri.getPath();
int cut = fileName.lastIndexOf('/');
if (cut != -1) {
fileName = fileName.substring(cut + 1);
}
}
return fileName;
}
openFileChooser()
方法即可。注意:在 Android 10 及更高版本中,外部存儲機制發生了變化。為了訪問外部存儲,需要在運行時請求分區存儲權限。具體信息可參考 官方文檔。