本文執行個體講述了Android實現檔案的儲存與讀取功能。分享給大家供大家參考,具體如下:
註: 在Activity中有 getFileDir() 和 getCacheDir(); 方法可以獲得當前的手機內建的儲存空間中的當前包檔案的路徑
getFileDir() ----- /data/data/cn.xxx.xxx(當前包)/files
getCacheDir() ----- /data/data/cn.xxx.xxx(當前包)/cache
1. 編寫檔案讀取與寫入功能實作類別 FileService
package cn.android.service;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import android.content.Context;import android.util.Log;/*** 檔案儲存與讀取功能實作類別* @author Administrator** 2010-6-28 下午08:15:18*/public class FileService { public static final String TAG = "FileService"; private Context context; //得到傳入的內容物件的引用 public FileService(Context context) { this.context = context; } /** * 儲存檔案 * * @param fileName 檔案名稱 * @param content 檔案內容 * @throws Exception */ public void save(String fileName, String content) throws Exception { // 由於頁面輸入的都是文本資訊,所以當檔案名稱不是以.txt尾碼名結尾時,自動加上.txt尾碼 if (!fileName.endsWith(".txt")) { fileName = fileName + ".txt"; } byte[] buf = fileName.getBytes("iso8859-1"); Log.e(TAG, new String(buf,"utf-8")); fileName = new String(buf,"utf-8"); Log.e(TAG, fileName); // Context.MODE_PRIVATE:為預設操作模式,代表該檔案是私人資料,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原檔案的內容,如果想把新寫入的內容追加到原檔案中。可以使用Context.MODE_APPEND // Context.MODE_APPEND:模式會檢查檔案是否存在,存在就往檔案追加內容,否則就建立新檔案。 // Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有許可權讀寫該檔案。 // MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取;MODE_WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入。 // 如果希望檔案被其他應用讀和寫,可以傳入: // openFileOutput("output.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); FileOutputStream fos = context.openFileOutput(fileName, context.MODE_PRIVATE); fos.write(content.getBytes()); fos.close(); } /** * 讀取檔案內容 * * @param fileName 檔案名稱 * @return 檔案內容 * @throws Exception */ public String read(String fileName) throws Exception { // 由於頁面輸入的都是文本資訊,所以當檔案名稱不是以.txt尾碼名結尾時,自動加上.txt尾碼 if (!fileName.endsWith(".txt")) { fileName = fileName + ".txt"; } FileInputStream fis = context.openFileInput(fileName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; //將讀取後的資料放置在記憶體中---ByteArrayOutputStream while ((len = fis.read(buf)) != -1) { baos.write(buf, 0, len); } fis.close(); baos.close(); //返回記憶體中儲存的資料 return baos.toString(); }}
2. 編寫Activity類:
package cn.android.test;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import cn.android.service.FileService;public class TestAndroidActivity extends Activity { /** Called when the activity is first created. */ //得到FileService對象 private FileService fileService = new FileService(this); //定義視圖中的filename輸入框對象 private EditText fileNameText; //定義視圖中的contentText輸入框對象 private EditText contentText; //定義一個土司提示對象 private Toast toast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //得到視圖中的兩個輸入框和兩個按鈕的對象引用 Button button = (Button)this.findViewById(R.id.button); Button read = (Button)this.findViewById(R.id.read); fileNameText = (EditText) this.findViewById(R.id.filename); contentText = (EditText) this.findViewById(R.id.content); //為儲存按鈕添加儲存事件 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String fileName = fileNameText.getText().toString(); String content = contentText.getText().toString(); //當檔案名稱為空白的時候,提示使用者檔案名稱為空白,並記錄日誌。 if(isEmpty(fileName)) { toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.w(fileService.TAG, "The file name is empty"); return; } //當檔案內容為空白的時候,提示使用者檔案內容為空白,並記錄日誌。 if(isEmpty(content)) { toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_content, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.w(fileService.TAG, "The file content is empty"); return; } //當檔案名稱和內容都不為空白的時候,調用fileService的save方法 //當成功執行的時候,提示使用者儲存成功,並記錄日誌 //當出現異常的時候,提示使用者儲存失敗,並記錄日誌 try { fileService.save(fileName, content); toast = Toast.makeText(TestAndroidActivity.this, R.string.success, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.i(fileService.TAG, "The file save successful"); } catch (Exception e) { toast = Toast.makeText(TestAndroidActivity.this, R.string.fail, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.e(fileService.TAG, "The file save failed"); } } }); //為讀取按鈕添加讀取事件 read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //得到檔案名稱輸入框中的值 String fileName = fileNameText.getText().toString(); //如果檔案名稱為空白,則提示使用者輸入檔案名稱,並記錄日誌 if(isEmpty(fileName)) { toast = Toast.makeText(TestAndroidActivity.this, R.string.empty_filename, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.w(fileService.TAG, "The file name is empty"); return; } //調用fileService的read方法,並將讀取出來的內容放入到常值內容輸入框裡面 //如果成功執行,提示使用者讀取成功,並記錄日誌。 //如果出現異常資訊(例:檔案不存在),提示使用者讀取失敗,並記錄日誌。 try { contentText.setText(fileService.read(fileName)); toast = Toast.makeText(TestAndroidActivity.this, R.string.read_success, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.i(fileService.TAG, "The file read successful"); } catch (Exception e) { toast = Toast.makeText(TestAndroidActivity.this, R.string.read_fail, Toast.LENGTH_LONG); toast.setMargin(RESULT_CANCELED, 0.345f); toast.show(); Log.e(fileService.TAG, "The file read failed"); } } }); } //編寫一個isEmpty方法,判斷字串是否為空白 private boolean isEmpty(String s) { if(s == null || "".equals(s.trim())) { return true; } return false; }}
3.檔案布局檔案:main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/filename" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/filename" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/content" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:minLines="3" android:id="@+id/content" /> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button" android:text="@string/save" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/read" android:text="@string/read" /> </LinearLayout></LinearLayout>
PS:由於我在測試這個功能的時候發現檔案名稱無法使用中文(sdk2.2 + 模擬器),如果有哪為高手無意中瀏覽此文章後,能對這個問題予以指點,我將感激不盡。呵呵。
更多關於Android相關內容感興趣的讀者可查看本站專題:《Android檔案操作技巧匯總》、《Android編程之activity操作技巧總結》、《Android視圖View技巧總結》、《Android操作SQLite資料庫技巧總結》、《Android操作json格式資料技巧總結》、《Android資料庫操作技巧總結》、《Android編程開發之SD卡操作方法匯總》、《Android開發入門與進階教程》、《Android資源操作技巧匯總》及《Android控制項用法總結》
希望本文所述對大家Android程式設計有所協助。