Android實(shí)現(xiàn)文件的保存與讀取功能示例
本文實(shí)例講述了Android實(shí)現(xiàn)文件的保存與讀取功能。分享給大家供大家參考,具體如下:
注: 在Activity中有 getFileDir() 和 getCacheDir(); 方法可以獲得當(dāng)前的手機(jī)自帶的存儲(chǔ)空間中的當(dāng)前包文件的路徑
getFileDir() ----- /data/data/cn.xxx.xxx(當(dāng)前包)/files
getCacheDir() ----- /data/data/cn.xxx.xxx(當(dāng)前包)/cache
1. 編寫文件讀取與寫入功能實(shí)現(xiàn)類 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; /** * 文件保存與讀取功能實(shí)現(xiàn)類 * @author Administrator * * 2010-6-28 下午08:15:18 */ public class FileService { public static final String TAG = "FileService"; private Context context; //得到傳入的上下文對(duì)象的引用 public FileService(Context context) { this.context = context; } /** * 保存文件 * * @param fileName 文件名 * @param content 文件內(nèi)容 * @throws Exception */ public void save(String fileName, String content) throws Exception { // 由于頁面輸入的都是文本信息,所以當(dāng)文件名不是以.txt后綴名結(jié)尾時(shí),自動(dòng)加上.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:為默認(rèn)操作模式,代表該文件是私有數(shù)據(jù),只能被應(yīng)用本身訪問,在該模式下,寫入的內(nèi)容會(huì)覆蓋原文件的內(nèi)容,如果想把新寫入的內(nèi)容追加到原文件中??梢允褂肅ontext.MODE_APPEND // Context.MODE_APPEND:模式會(huì)檢查文件是否存在,存在就往文件追加內(nèi)容,否則就創(chuàng)建新文件。 // Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應(yīng)用是否有權(quán)限讀寫該文件。 // MODE_WORLD_READABLE:表示當(dāng)前文件可以被其他應(yīng)用讀??;MODE_WORLD_WRITEABLE:表示當(dāng)前文件可以被其他應(yīng)用寫入。 // 如果希望文件被其他應(yīng)用讀和寫,可以傳入: // 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(); } /** * 讀取文件內(nèi)容 * * @param fileName 文件名 * @return 文件內(nèi)容 * @throws Exception */ public String read(String fileName) throws Exception { // 由于頁面輸入的都是文本信息,所以當(dāng)文件名不是以.txt后綴名結(jié)尾時(shí),自動(dòng)加上.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; //將讀取后的數(shù)據(jù)放置在內(nèi)存中---ByteArrayOutputStream while ((len = fis.read(buf)) != -1) { baos.write(buf, 0, len); } fis.close(); baos.close(); //返回內(nèi)存中存儲(chǔ)的數(shù)據(jù) 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對(duì)象 private FileService fileService = new FileService(this); //定義視圖中的filename輸入框?qū)ο? private EditText fileNameText; //定義視圖中的contentText輸入框?qū)ο? private EditText contentText; //定義一個(gè)土司提示對(duì)象 private Toast toast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //得到視圖中的兩個(gè)輸入框和兩個(gè)按鈕的對(duì)象引用 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(); //當(dāng)文件名為空的時(shí)候,提示用戶文件名為空,并記錄日志。 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; } //當(dāng)文件內(nèi)容為空的時(shí)候,提示用戶文件內(nèi)容為空,并記錄日志。 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; } //當(dāng)文件名和內(nèi)容都不為空的時(shí)候,調(diào)用fileService的save方法 //當(dāng)成功執(zhí)行的時(shí)候,提示用戶保存成功,并記錄日志 //當(dāng)出現(xiàn)異常的時(shí)候,提示用戶保存失敗,并記錄日志 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; } //調(diào)用fileService的read方法,并將讀取出來的內(nèi)容放入到文本內(nèi)容輸入框里面 //如果成功執(zhí)行,提示用戶讀取成功,并記錄日志。 //如果出現(xiàn)異常信息(例:文件不存在),提示用戶讀取失敗,并記錄日志。 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"); } } }); } //編寫一個(gè)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:由于我在測(cè)試這個(gè)功能的時(shí)候發(fā)現(xiàn)文件名無法使用中文(sdk2.2 + 模擬器),如果有哪為高手無意中瀏覽此文章后,能對(duì)這個(gè)問題予以指點(diǎn),我將感激不盡。呵呵。
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android文件操作技巧匯總》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android視圖View技巧總結(jié)》、《Android操作SQLite數(shù)據(jù)庫技巧總結(jié)》、《Android操作json格式數(shù)據(jù)技巧總結(jié)》、《Android數(shù)據(jù)庫操作技巧總結(jié)》、《Android編程開發(fā)之SD卡操作方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
相關(guān)文章
Android獲取SDcard目錄及創(chuàng)建文件夾的方法
今天小編就為大家分享一篇Android獲取SDcard目錄及創(chuàng)建文件夾的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08基于Android studio3.6的JNI教程之ncnn人臉檢測(cè)mtcnn功能
這篇文章主要介紹了基于Android studio3.6的JNI教程之ncnn之人臉檢測(cè)mtcnn功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03ANDROID BottomNavigationBar底部導(dǎo)航欄的實(shí)現(xiàn)示例
本篇文章主要介紹了ANDROID BottomNavigationBar底部導(dǎo)航欄的實(shí)現(xiàn)示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-10-10Android使用RadioGroup實(shí)現(xiàn)底部導(dǎo)航欄
這篇文章主要為大家詳細(xì)介紹了Android使用RadioGroup實(shí)現(xiàn)底部導(dǎo)航欄,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08Android自定義控件實(shí)現(xiàn)隨手指移動(dòng)的小球
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)隨手指移動(dòng)的小球,隨著手指觸摸移動(dòng)而移動(dòng)的效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10利用百度地圖Android sdk高仿微信發(fā)送位置功能及遇到的問題
這篇文章給大家介紹了利用百度地圖Android sdk高仿微信發(fā)送位置功能,在實(shí)現(xiàn)此功能的時(shí)候遇到點(diǎn)小問題,下面小編給大家列出來,需要的朋友參考下吧2017-12-12