編輯:關於Android編程
本文實例講述了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程序設計有所幫助。
紅米note4什麼時候上市?紅米Note4真機疑曝光
前兩天,一張小米的宣傳海報在網上曝光,海報中是小米剛簽下的紅米代言人之一劉昊然,而亮點在於他手中的手機,這部手機采用了雙攝像頭設計,應該是一部還未發布的紅米
深入淺出學習Android ListView基礎
ListView 簡介ListView 是安卓裡常用的控件, 本文介紹一下常用用法,以及優化等方法1、改寫activity_main.xml<LinearLayou
Android EventBus3.0使用及源碼解析
叨了個叨最近因為換工作的一些瑣事搞的我一個頭兩個大,也沒怎麼去學新東西,實在是有些愧疚。新項目用到了EventBus3.0,原來只是聽說EventBus的鼎鼎大名,一直沒
Android全新的SwipeRefreshLayout控件教程
SwipeRefreshLayout感覺是Google在吸收了PullToRefresh-ListView,ActionBarPullToRefresh之後實現的goog