Android: 寫文件到SD卡

考慮到SD卡可能沒有被mount,或者其他各種情況,操作SD卡上的文件總需要各種狀態的判斷。主要是使用Environment類裏的一些接口進行判斷:
[code]
private void writeFileToSD() {
String sdStatus = Environment.getExternalStorageState();
if(!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
Log.d("TestFile", "SD card is not avaiable/writeable right now.");
return;
}
try {
String pathName="/sdcard/test/";
String fileName="file.txt";
File path = new File(pathName);
File file = new File(pathName + fileName);
if( !path.exists()) {
Log.d("TestFile", "Create the path:" + pathName);
path.mkdir();
}
if( !file.exists()) {
Log.d("TestFile", "Create the file:" + fileName);
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
String s = "this is a test string writing to file.";
byte[] buf = s.getBytes();
stream.write(buf);
stream.close();

} catch(Exception e) {
Log.e("TestFile", "Error on writeFilToSD.");
e.printStackTrace();
}
}
[/code]
[color=red]需要加入權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
[/color]

看文檔說,可以使用Context.getExternalFilesDir來取得一個特殊的文件夾,該文件夾對USER不可見,最重要的是:[color=red]當系統卸載該程序時,會自動刪除該目錄下的文件。[/color]

如果不需要往SD卡上寫文件,可以直接用以下簡單代碼:
[code]
private void writeFile() {
try {
FileOutputStream stream = openFileOutput("testfile.txt", Context.MODE_WORLD_WRITEABLE);
String s = "this is a test string writing to file.";
byte[] buf = s.getBytes();
stream.write(buf);
stream.close();
}
catch (FileNotFoundException e) {
Log.d("TestFile", "File not found.");
}
catch (IOException e) {
Log.d("TestFile", "File write error.");
}
}
[/code]
該文件會被放置於data/data/your_app_package_name/files下。

[color=red]
值得注意的是,我們可以在程序運行期間動態檢查SD卡是否可用。大致就是通過註冊BroadcastReceiver實現,這個官方文檔裏有提到:
[/color]
[code]
void startWatchingExternalStorage() {
mExternalStorageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
Log.i("test", "Storage: " + intent.getData());
updateExternalStorageState();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
registerReceiver(mExternalStorageReceiver, filter);
updateExternalStorageState();
}
void stopWatchingExternalStorage() {
unregisterReceiver(mExternalStorageReceiver);
}
[/code]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章