国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android實現文件的保存與讀取功能示例

2019-12-12 05:39:17
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 凌海市| 壶关县| 陵水| 澳门| 自治县| 木里| 南康市| 略阳县| 九台市| 吴忠市| 湟中县| 泾源县| 武威市| 柞水县| 荔波县| 双流县| 河间市| 宜宾市| 信丰县| 遂宁市| 永康市| 林周县| 泰来县| 武定县| 鞍山市| 荆州市| 独山县| 龙陵县| 霍城县| 芮城县| 延寿县| 霍山县| 西乌| 长顺县| 仪征市| 阜城县| 西华县| 永昌县| 永昌县| 玉林市| 古交市|