編輯:關於 Android 程式設計
Android 的檔案存取圍繞著 Context 的 openFileOutput 與 openFileInput 展開,位置固定在 /data/data/<package name>/files/。本文以「輸入檔名與內容、按鈕存檔」為例,把寫入與讀取兩個方向都走完。
畫面上放兩個輸入框(檔名、內容)與一個保存按鈕,點擊時把值取出交給 service 層處理:
public class FileActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
private final class ButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
EditText filenameText = (EditText) findViewById(R.id.filename);
EditText contentText = (EditText) findViewById(R.id.filecontent);
String filename = filenameText.getText().toString();
String content = contentText.getText().toString();
FileService service = new FileService(getApplicationContext());
// 傳 getApplicationContext() 或 this 皆可,Activity 本身也是 Context
try {
service.save(filename, content);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
e.printStackTrace();
}
}
}
}
public class FileService {
private Context context;
public FileService(Context context) { this.context = context; }
public void save(String filename, String content) throws Exception {
FileOutputStream outStream =
context.openFileOutput(filename, Context.MODE_PRIVATE);
outStream.write(content.getBytes());
outStream.close(); // 一定要關,否則內容可能沒落地
}
}
openFileOutput 的第一個參數是檔名,不可包含路徑分隔符「/」;檔案不存在時 Android 會自動建立,位置在 /data/data/<package name>/files/。想看實際檔案,可在 Eclipse 中開啟 File Explorer 視圖(Window → Show View → Other → Android → File Explorer),展開該目錄即可。
content.getBytes() 使用系統預設字元編碼,在 Android 上就是 UTF-8,所有字串都能正確編碼;若不指定而系統無預設編碼,則會退回 ISO-8859-1。跨語言情境下建議明確寫成 getBytes("UTF-8")。
若確實要讓其他應用讀寫,可將旗標相加傳入:
openFileOutput("itcast.txt",
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
但這兩個模式在後續 Android 版本中已被弱化或移除,正是因為它繞過了 Android 的安全模型。跨應用分享檔案的正確做法是用 FileProvider 搭配內容 URI 並授予臨時權限。
Android 有一套自己的安全模型:應用程式(apk)安裝時,系統會為它分配一個 userid。當該應用要存取檔案等資源時,需要 userid 相符。因此任何應用建立的檔案、SharedPreferences、資料庫預設都是私有的,位於 /data/data/<package name>/ 下,其他程式無法存取——除非建立時明確指定了 WORLD_READABLE 或 WORLD_WRITEABLE。理解這一點,就不會把「讀不到別人的檔案」誤判為 bug。
在 FileService 中補上讀取方法,用輸入流逐段讀進記憶體再轉為字串:
public String read(String filename) throws Exception {
FileInputStream inputStream = context.openFileInput(filename);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// read() 回傳 -1 代表讀完;否則回傳本次實際讀到的位元組數
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
return new String(outputStream.toByteArray());
}
這裡有個常見錯誤值得強調:inputStream.read(buffer) 只讀「滿一個陣列」或到檔尾為止,並不保證一次讀完。因此必須放在迴圈裡反覆呼叫,直到回傳 -1。少了迴圈,大檔案就會被截斷。
用 AndroidTestCase 寫一個簡單的讀取測試:
public class readTest extends AndroidTestCase {
private static final String TAG = "FileServiceTest";
public void testRead() throws Exception {
FileService service = new FileService(this.getContext());
String result = service.read("lidewei.txt");
Log.i(TAG, result);
}
}
同時要在 AndroidManifest.xml 中掛上測試用的 instrumentation 與 test runner 函式庫:
<uses-library android:name="android.test.runner" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.credream.file" />
完成後對測試類按右鍵執行,並用 logcat 的過濾器只看 FileServiceTest 這個 tag,就能確認檔案內容是否如預期讀出。
行動電源怎麼用?充電、指示燈與使用教學
行動電源可先在外出前充飽電,再為手機、平板等裝置補充電力。以下整理指示燈、充電與使用方式。指示燈說明紅燈閃爍通常代表電量不足,綠燈長亮代表電力充足。為行動電源充電時,紅燈
Android 自定義 ViewGroup:打造可配置子 View 位置的容器
自定義 View 能畫出單一元件,自定義 ViewGroup 則能決定多個子元件如何排列。若要實作特殊版面,例如四散定位、拖曳卡片或側滑選單,就必須理解 ViewGrou
在 Windows 10 上安裝 React Native Android 開發環境
搭建 React Native 環境 首先你必須裝好 Java JDK,且版本要在 1.8 以上。下載並安裝 JDK 1.8(64 位或 32 位)後,記得配置好相關的環
ListView 下拉動態渲染資料的實作與四大坑點
本文記錄如何在 ListView 中做到滾動到底部時逐步渲染資料。 資料規劃的兩種思路 假設資料總量在 100 筆以上,一般有以下兩種處理方式。 方案一:一次性把 10