本文實例講述了Android開發之SD卡文件操作。分享給大家供大家參考,具體如下:
前面的文章中寫過直接操作手機自帶存儲器的程序,這次就接著上次文章協議下對sd卡的文件操作。與自帶存儲不同的是使用sd卡需要用戶授權
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
千萬要記住不能寫顛倒了,不然看不到結果
之后寫個方法來保存文件
public void saveToSD(String filename,String content) throws Exception{ //getExternalStorageDirectory()可以取得sd卡得路徑 File f=new File(Environment.getExternalStorageDirectory(),filename); FileOutputStream out2=new FileOutputStream(f); out2.write(content.getBytes()); out2.close();}最后就可以在控制層使用這個方法了,需要對SD卡得狀態作判斷,取得狀態可以使用Environment.getExternalStorageState(),如果可用才能保存文件,反之就提示“sd卡不存在或不可用”
package org.lxh.file;import org.lxh.service.FileService;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class FileActivity extends Activity { private FileService service; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); service=new FileService(this); Button button=(Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { EditText filename=(EditText)findViewById(R.id.filename); EditText content=(EditText)findViewById(R.id.content); try { if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ service.saveToSD(filename.getText().toString(), content.getText().toString()); Toast.makeText(FileActivity.this, R.string.success, 1).show(); }else{ Toast.makeText(FileActivity.this, R.string.sd, 1).show(); } //service.saveFile(filename.getText().toString(), content.getText().toString()); } catch (Exception e) { Toast.makeText(FileActivity.this, R.string.failure, 1).show(); Log.e("FileActivity", e.getMessage()); } } }); }}下面 把strings.xml也貼出來
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, FileActivity!</string> <string name="app_name">文件的讀取</string> <string name="filename">輸入文件名稱</string> <string name="content">輸入文件內容</string> <string name="button">保存</string> <string name="success">文件保存成功</string> <string name="failure">文件保存失敗</string> <string name="sd">sd卡不存在或不可用</string></resources>
到這里就可以對SD卡進行操作了,這次的東西比較少。
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android編程開發之SD卡操作方法匯總》、《Android文件操作技巧匯總》、《Android數據庫操作技巧總結》、《Android編程之activity操作技巧總結》、《Android開發入門與進階教程》、《Android資源操作技巧匯總》、《Android視圖View技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答