在实际的开发中,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(); } }