在實際的開發中,Android提供了5種數據存儲的方式:
1)文件存儲數據
2)使用SharedPreferences存儲數據
3)使用SQLite數據庫存儲數據
4)使用ContentProvide存儲數據
5)網絡存儲數據
一、文件存儲數據到內部存儲器
1)爲了保存文本到文件中,需要FileOutputStream類,openFileOutput方法用指定的模式打開一個指定的文件夾來寫入:
FileOutputStream fileOut = openFileOutput(“hello.txt”, Context.MODE_WORLD_WRITEABLE);
其中,有三種模式提供選擇:
Context.MODE_PRIVATE: 創建的文件只能被該應用程序讀寫
Context.MODE_WORLD_READABLE:允許其他應用程序讀取文件
Context.MODE_WORLD_WRITEABLE: 允許其他應用程序修改文件
2)爲了將字符流轉換爲字節流,需要OutputStreamWriter類的對象,並傳入FileOutputStream類的實例作爲參數:
OutputStreamWriter osw = newOutputStreamWriter(fileOut);
3)而讀取文件則需要用到FileInputStream類和InputStreamReader類:
FileInputStream fileInput = openFileInput(“hello.txt”);
InputStreamReader isr = new InputStreamReader(fileInput);
4)新建一個字符數組作爲緩衝器,把文件內容讀到緩衝器中,然後將其複製到String對象中
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = “”;
int charRead;
while((charRead = isr.read(inputBuffer)>0){
StringreadString = String.copyValueOf(inputBuffer, 0, charRead);
s +=readString;
inputBuffer= new char[READ_BLOCK_SIZE];
}
public class FilesActivity extends Activity {
EditText textBox;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textBox = (EditText)findViewById(R.id.txtText);
}
public void onClickSave(View v){
String str = textBox.getText().toString();
try {
FileOutputStream fileOut = openFileOutput("hello.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.write(str);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClickLoad(View v){
try {
FileInputStream fileInput = openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fileInput);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer)) > 0){
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
二、文件存儲數據到SD卡
返回sd卡的完整路徑:
File sdCard = Environment.getExternalStorageDirectory();
在SD卡中創建一個名問MyFiles的目錄,最終文件將會保存到這裏:
File directory = new File(sdCard.getAbsolutePath()+"/MyFiles");
directory.mkdir();
讀取SD卡需要在AndroidMinifest.xml文件中添加權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
其他的跟上面的一樣,下面看代碼:
public class FilesActivity extends Activity {
EditText textBox;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textBox = (EditText)findViewById(R.id.txtText);
}
public void onClickSave(View v){
String str = textBox.getText().toString();
try {
File sdCard = Environment.getExternalStorageDirectory();//返回sd卡的路徑
File directory = new File(sdCard.getAbsolutePath()+"/MyFiles");
directory.mkdir();
File file = new File(directory, "textfile.txt");
FileOutputStream fileOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.write(str);
osw.flush();
osw.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClickLoad(View v){
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/MyFiles");
File file = new File(directory, "textfile.txt");
FileInputStream fileIn;
fileIn = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer)) > 0){
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、使用SharedPreferences存儲數據
【存】
創建對象:
SharedPreferences sp = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
創建編輯器:
SharedPreferences.Editor editor = sp.edit();
往編輯器存入int、boolean、String等類型的數據分別使用對應的方法:
editor.putBoolean("flag", true);
editor.putInt("age", 40);
editor.putString("你好啊,請多多指教","message");
編輯器必鬚髮送出去才能生效:
editor.commit();
【取】
還是需要SharedPreferences 對象:
SharedPreferences sp =getSharedPreferences("FILE_NAME",MODE_PRIVATE);
與set對應,取出對應的數據是get,如getBoolean、getString等:
booleanflag = sp.getBoolean("flag",false);
int age =sp.getInt("age", 0);
String mess = sp.getString("message","No message");
public class MainActivity extends Activity {
private Button send,look;
private EditText input;
private TextView msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.msg = (TextView)findViewById(R.id.msg);
this.send = (Button)findViewById(R.id.send);
this.look = (Button)findViewById(R.id.look);
this.input = (EditText)findViewById(R.id.input);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("FILE_NAME", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("message",input.getText().toString());
editor.commit();
msg.setText("你有新的消息,請注意查收");
}
});
look.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("FILE_NAME", MODE_PRIVATE);
String mess = sp.getString("message", "No message");
msg.setText(mess);
}
});
}
}
三、使用靜態資源
也就是使用在res/raw文件夾下的文件。使用Activity類的getResources方法返回一個Resources對象,然後使用其openRawResource方法打開包含在res/raw文件夾下的文件。
public void onClickGetSources(View v){
InputStream is = getBaseContext().getResources().openRawResource(R.raw.text);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = null;
try {
while((str = br.readLine())!=null){
Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
}
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}