編輯:關於 Android 程式設計
Android 的存儲方式有好幾種,內部存儲是最基礎的一種。它的特點是每個應用擁有自己私有的目錄,卸載時相關數據會被系統自動清除,因此適合存放不需要與外部共享的數據。

一個輸入框加一個保存按鈕:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="28dp"
android:layout_marginTop="17dp"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="54dp"
android:text="保存信息" />
</RelativeLayout>
/**
* 使用內部存儲,應用卸載時相關信息會被清除
*/
public class FileService {
private Context context;
public FileService(Context context) {
this.context = context;
}
/**
* 保存內容到文件
* @param fileName 文件名
* @param mode 打開模式
* @param data 數據緩衝區
*/
public boolean saveContentToFile(String fileName, int mode, byte[] data) {
boolean flag = false;
FileOutputStream outputStream = null;
try {
outputStream = context.openFileOutput(fileName, mode);
outputStream.write(data, 0, data.length);
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try { outputStream.close(); } catch (Exception e2) { }
}
}
return flag;
}
/** 讀取文件內容 */
public String readContentFromFile(String fileName) {
FileInputStream fileInputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
fileInputStream = context.openFileInput(fileName);
int len = 0;
byte[] data = new byte[1024];
while ((len = fileInputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
return new String(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try { fileInputStream.close(); } catch (IOException e) { }
}
}
return "";
}
/** 保存文件到自定義子目錄 */
public boolean saveCacheFile(String fileName, byte[] data) {
boolean flag = false;
File file = context.getFilesDir();
FileOutputStream outputStream = null;
try {
File folderFile = new File(file.getAbsoluteFile() + "/txt");
if (!folderFile.exists()) {
folderFile.mkdirs(); // 遞歸創建目錄
}
outputStream = new FileOutputStream(folderFile.getAbsolutePath() + "/" + fileName);
outputStream.write(data, 0, data.length);
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try { outputStream.close(); } catch (IOException e) { }
}
}
return flag;
}
/** 列出目錄下的所有文件絕對路徑 */
public void listCacheFile() {
File file = context.getFilesDir();
File root = new File(file.getAbsoluteFile() + "/txt");
File[] listFiles = root.listFiles();
if (listFiles == null) return;
for (File file2 : listFiles) {
System.err.println("--->>" + file2.getAbsolutePath());
}
}
}
public class MainActivity extends Activity {
private Button button;
private EditText editText;
private FileService fileService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
editText = (EditText) this.findViewById(R.id.editText1);
fileService = new FileService(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String valueString = editText.getText().toString().trim();
boolean flag = fileService.saveContentToFile(
"bb.txt", Context.MODE_APPEND, valueString.getBytes());
if (flag) {
Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
public class MyTest extends AndroidTestCase {
private static final String TAG = "MyTest";
/** 保存數據 */
public void save() {
FileService fileService = new FileService(getContext());
boolean flag = fileService.saveContentToFile("aa.txt", Context.MODE_APPEND, "nihao".getBytes());
Log.i(TAG, "--->>" + flag);
}
/** 讀取數據 */
public void read() {
FileService fileService = new FileService(getContext());
String msg = fileService.readContentFromFile("bb.txt");
Log.i(TAG, "--->>" + msg);
}
/** 寫入子目錄 */
public void testChaceFile() {
FileService fileService = new FileService(getContext());
fileService.saveCacheFile("hello.txt", "hello world!".getBytes());
}
/** 列出子目錄文件 */
public void testListFile() {
FileService fileService = new FileService(getContext());
fileService.listCacheFile();
}
}

保存成功後,可以在 data/data/包名/files 目錄下找到對應文件(需要 root 或用 run-as 才能訪問)。

1、openFileOutput 的模式參數:MODE_PRIVATE 會覆蓋原文件,MODE_APPEND 則追加寫入。示例裡用了 MODE_APPEND,所以多次點擊按鈕內容會不斷累加。
2、files 與 cache 的區別:getFilesDir() 下的文件是持久的,系統不會主動清理;getCacheDir() 下的文件在內存不足時可能被系統刪除,適合放臨時數據。原始文章示例把方法命名為 saveCacheFile 但實際寫到了 files/txt 目錄,這裡提醒一下,真正想用緩存目錄應改為 context.getCacheDir()。
3、內部存儲不需要讀寫權限,這是它相對外部存儲的一大優勢,不用處理 Android 6.0 以上的動態授權。
4、編碼要顯式指定,new String(bytes) 在目標機與開發機默認編碼不一致時會出現亂碼,正式代碼建議寫成 new String(bytes, "UTF-8")。
Xamarin Android 開發教程——下載與安裝 Xamarin 全流程
Xamarin Android 開發教程之下載安裝 Xamarin 早期版本的 Xamarin 在安裝時會檢查系統中是否已具備前置環境,而後來的版本則只提供安裝步驟引導,
Android 產品研發(十九)——Android Studio 中的單元測試實踐
上一篇整理了 WebView 的常見問題:效能優化、注入 Cookie、Activity 退出時清理 WebView 導致的報錯、Java 與 JS 互相呼叫、WebVi
動手做一款 Android 拼圖小遊戲:自定義 View 與動畫的綜合練習
一、需求描述 拼圖是個經典的益智玩法:把一張圖片切成若干塊、打亂之後,讓玩家在限定時間內還原。這個案例的規則很直覺——隨意點選兩塊即可交換位置,不需要拖曳,因此手機操作成
以自定義滑動開關按鈕為例,圖文透視 Android 自定義 View 繪制
自定義 View 常常是 Android 開發者面前的一道坎。本文不談空洞理論,直接拿一個滑動開關按鈕開刀,把 measure、layout、draw 三個環節串起來講清