SharedPreferences對象能夠讓你去儲存一些“索引值對”類型的資料,比如使用者id,生日,性別,身份證 號等等。但是,有的時候你需要去使用傳統的檔案系統去儲存資料。例如你可能想要去儲存一篇文章,而這 篇文章要被展示在你的應用中。在Android系統中,你也可以使用java.io包去實現這個功能。
在 Android系統中,第一種儲存檔案的方法是儲存到內部裝置。下面展示如何儲存用書輸入的字串到內部儲存 裝置。
1. 建立一個工程,Files。
2. main.xml中的代碼。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Please enter some text" /> <EditText android:id="@+id/txtText1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btnSave" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickSave" android:text="Save" /> <Button android:id="@+id/btnLoad" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickLoad" android:text="Load" /> </LinearLayout>
3. FilesActivity.java中的代碼。
package net.manoel.Files; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import net.learn2develop.Files.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class FilesActivity extends Activity { EditText textBox; static final int READ_BLOCK_SIZE = 100; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textBox = (EditText) findViewById(R.id.txtText1); } public void onClickSave(View view) { String str = textBox.getText().toString(); try { FileOutputStream fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); //---write the string to the file--- osw.write(str); osw.flush(); osw.close(); //---display file saved message--- Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show(); //---clears the EditText--- textBox.setText(""); } catch (IOException ioe) { ioe.printStackTrace(); } } public void onClickLoad(View view) { try { FileInputStream fIn = openFileInput("textfile.txt"); InputStreamReader isr = new InputStreamReader(fIn); char[] inputBuffer = new char[READ_BLOCK_SIZE]; String s = ""; int charRead; while ((charRead = isr.read(inputBuffer))>0) { //---convert the chars to a String--- String readString = String.copyValueOf(inputBuffer, 0, charRead); s += readString; inputBuffer = new char[READ_BLOCK_SIZE]; } //---set the EditText to the text that has been // read--- textBox.setText(s); Toast.makeText(getBaseContext(), "File loaded successfully!", Toast.LENGTH_SHORT).show(); } catch (IOException ioe) { ioe.printStackTrace(); } } }