編輯:關於 Android 程式設計
除了 SharedPreferences,Android 還允許我們直接把資料存成檔案。本文以一個簡單的姓名與年齡紀錄為例,示範如何利用內部儲存寫入與讀取資料,並進一步說明其他應用程式如何跨應用訪問這些檔案。
寫入時使用 openFileOutput,並透過 MODE_APPEND 達到附加寫入的效果;讀取時則用 openFileInput 把位元組讀進來,再轉成字串顯示。這種方式適合保存純文字類的資料。
參考程式碼 如下:
public class MainActivity extends Activity {
EditText mname, mage;
TextView mtv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mname = (EditText) findViewById(R.id.editText1);
mage = (EditText) findViewById(R.id.editText2);
mtv = (TextView) findViewById(R.id.textView1);
}
public void onClick(View v) {
String name = mname.getText().toString();
int age = Integer.parseInt(mage.getText().toString());
String cont = "name=" + name + ",age=" + age + "\n";
try {
int id = v.getId();
// 內部保存
if (id == R.id.button1) {
FileOutputStream fos = this.openFileOutput("mytext.txt",
Context.MODE_APPEND | Context.MODE_WORLD_WRITEABLE
| Context.MODE_WORLD_READABLE);
fos.write(cont.getBytes());
fos.close();
Toast.makeText(this, "寫入完成", 1).show();
}
// 讀取
else if (id == R.id.button2) {
FileInputStream fis = this.openFileInput("mytext.txt");
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
String str = new String(bytes);
mtv.setText(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
內部儲存檔案位於應用程式的私有目錄,其他程式若要讀寫,可以透過絕對路徑,或利用 createPackageContext 取得對應的 Context 再操作。以下程式碼示範了這幾種跨應用的訪問方式。
參考程式碼 如下:
public class MainActivity extends Activity {
TextView mcontent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontent=(TextView) findViewById(R.id.textView1);
}
public void onClick(View v){
switch (v.getId()) {
case R.id.button1:
try {
readRemoteFileByAbslutePath();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.button2:
try {
WriteRemoteFileByAbslutePath();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
/**
* 通過文件絕對路徑讀取遠程文件
* @throws Exception
*/
public void readRemoteFileByAbslutePath() throws Exception{
String path = "/data/data/com.nanguabing.filedemo/files/mytext.txt" ;
FileInputStream fis = new FileInputStream(path);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
String str = new String(bytes);
mcontent.setText(str);
Log.i("Other", str);
}
/**
* 通過文件絕對路徑讀取遠程文件
* @throws Exception
*/
public void WriteRemoteFileByAbslutePath() throws Exception{
String path = "/data/data/com.nanguabing.filedemo/files/mytext.txt" ;
FileOutputStream fos = new FileOutputStream(path,true);
fos.write("other write! ".getBytes());
fos.close();
Log.i("Other", "other write over!");
}
/**
* 通過包相關上下文寫入遠程文件
* @throws Exception
*/
public void readRomoteByPackageContext() throws Exception {
String pname = "com.nanguabing.filedemo";
Context ctx = this.createPackageContext(pname,
Context.CONTEXT_IGNORE_SECURITY);
FileInputStream fis = ctx.openFileInput("mytext.txt");
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
Log.i("Other",new String(bytes));
}
/**
* 通過包相關上下文寫入遠程文件
*/
public void readRomoteByPackageContext2() throws Exception {
String pname = "com.nanguabing.filedemo";
Context ctx = this.createPackageContext(pname,
Context.CONTEXT_INCLUDE_CODE);
FileInputStream fis = ctx.openFileInput("mytext.txt");
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
Log.i("Other",new String(bytes));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
需要特別注意,跨應用直接訪問私有檔案在真實專案中並不被鼓勵,這類做法在較新的 Android 版本會受到存取限制。正式開發時,若要對外分享資料,建議使用 ContentProvider 或 FileProvider 等更安全的機制。
Android DiffUtil 全解析:RecyclerView 增量刷新與局部更新
一、它解決了什麼問題 DiffUtil 是 support-v7:24.2.0 引入的工具類,作用是比較新老兩個數據集,算出從舊數據到新數據的最小改動集合。說到數據集,搭
Stagefright 音視頻輸出流程解析:從解碼 Buffer 到渲染與同步
數據處理流程回顧 Stagefright 的音視頻輸出,是從解碼後的 Buffer 開始。前一篇已說明數據如何被讀取、解碼並放入 Buffer,本篇接著分析音視頻如何被渲
Android 自訂 RatingBar:自由控制星星大小、間距與半星
做商家評分、商品好評度這類功能時,你一定會遇到系統內建的 RatingBar——它最大的問題是星星間距與尺寸幾乎無法調整,只能拿小小的預設圖去硬湊,設計稿永遠對不上。所以
Android 動態資源載入原理與換膚實作剖析
換膚、主題切換、插件化資源的底層原理,其實都指向同一件事:能不能讓 App 在執行期讀到「另一個 APK」裡的資源。要回答這個問題,得先弄清楚系統原生的 Resource