Android数据存储方式(一)文件

来源:互联网 发布:汉王人脸考勤机数据库 编辑:程序博客网 时间:2024/05/16 06:36

版权所有:http://blog.csdn.net/wulianghuan/article/details/8607573

很多时候我们开发的软件需要对处理后的数据进行存储,以供再次访问。Android为数据存储提供了如下几种方式:

1、文件

2、SharedPreferences(偏好参数)

3、SQLite数据库

4、内容提供者(Content provider)

5、网络


本篇介绍第一种存储方式:文件,我们采用文件来保存用户输入的数据,这里用到的是IO输入输出流对象,和使用SDCard的相关权限。

我们提供一个界面,供用户输入文件名和内容,然后可以打开来查看内容,以下是简单的界面截图:




当我们点击保存按钮之后,文件将保存到系统存储空间中,点击保存到SD卡则保存文件到SDCard,点击读取数据来获取数据。

工程目录结构:



源代码:

main.xml

[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/fileName" />  
  11.     <EditText   
  12.         android:id="@+id/filename"  
  13.         android:layout_width="fill_parent"  
  14.         android:layout_height="wrap_content"/>  
  15.     <TextView  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="@string/content" />  
  19.     <EditText   
  20.         android:id="@+id/content"  
  21.         android:layout_width="fill_parent"  
  22.         android:layout_height="wrap_content"/>  
  23.     <Button   
  24.         android:id="@+id/save"  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="@string/save"/>  
  28.     <Button   
  29.         android:id="@+id/saveToSdCard"  
  30.         android:layout_width="fill_parent"  
  31.         android:layout_height="wrap_content"  
  32.         android:text="@string/saveToSDCard"/>  
  33.     <Button   
  34.         android:id="@+id/read"  
  35.         android:layout_width="fill_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:text="@string/read"/>  
  38. </LinearLayout>  

read.xml
[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/filecontent"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"/>  
  11. </LinearLayout>  


Strings.xml
[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, MainActivity!</string>  
  4.     <string name="app_name">文件存储应用</string>  
  5.     <string name="fileName">文件名</string>  
  6.     <string name="content">文件内容</string>  
  7.     <string name="save">保存</string>  
  8.     <string name="saveToSDCard">保存数据到SD卡</string>  
  9.     <string name="read">读取数据</string>  
  10.     <string name="fileSaveException">文件保存出现异常</string>  
  11.     <string name="sdCardException">SD卡不存在,或者写保护</string>  
  12.     <string name="fileSaveSuccess">文件保存成功</string>  
  13. </resources>  


MainActivity.Java

[html] view plain copy print?
  1. package com.preferences.activity;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import com.preferences.service.PreferencesService;  
  6.   
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.widget.EditText;  
  11. import android.widget.Toast;  
  12.   
  13. public class MainActivity extends Activity {  
  14.     private EditText name;  
  15.     private EditText age;  
  16.     private PreferencesService service;  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.         name = (EditText)findViewById(R.id.name);  
  22.         age = (EditText)findViewById(R.id.age);  
  23.         service = new PreferencesService(MainActivity.this);  
  24.         //打开时读取保存的参数  
  25.         Map<String,String> params = service.getPreferences();  
  26.         name.setText(params.get("username"));  
  27.         age.setText(params.get("age"));  
  28.     }  
  29.     public void save(View v){  
  30.         String userName = name.getText().toString();  
  31.         int userAge = Integer.parseInt(age.getText().toString());  
  32.         service.save(userName, userAge);  
  33.         Toast.makeText(MainActivity.this, "保存成功", 1).show();  
  34.     }  
  35. }  

FileReadActivity.java
[html] view plain copy print?
  1. package com.file.activity;  
  2.   
  3. import java.io.IOException;  
  4. import android.app.Activity;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.widget.TextView;  
  8. import com.file.service.FileService;  
  9.   
  10. public class FileReadActivity extends Activity{  
  11.     private TextView content;  
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.read);  
  16.         content = (TextView)findViewById(R.id.filecontent);  
  17.         FileService fileService =new FileService(getApplicationContext());  
  18.         Intent intent = getIntent();  
  19.         String fileName = intent.getStringExtra("fileName");  
  20.         try {  
  21.             content.setText(fileService.read(fileName));  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.     }  
  26.       
  27. }  

FileService.java
[html] view plain copy print?
  1. package com.file.service;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import android.content.Context;  
  10. import android.os.Environment;  
  11.   
  12. public class FileService {  
  13.     private Context context;  
  14.     public FileService(Context context) {  
  15.         super();  
  16.         this.context = context;  
  17.     }  
  18.     /**  
  19.      * 保存文件  
  20.      * @param fileName 文件名称  
  21.      * @param content  文件内容  
  22.      * @throws IOException  
  23.      */  
  24.     public void save(String fileName, String content) throws IOException {  
  25.         //以私有方式读写数据,创建出来的文件只能被该应用访问  
  26.         FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);  
  27.         fileOutputStream.write(content.getBytes());  
  28.         fileOutputStream.close();  
  29.     }  
  30.       
  31.     /**  
  32.      * 保存文件  
  33.      * @param fileName 文件名称  
  34.      * @param content  文件内容  
  35.      * @throws IOException  
  36.      */  
  37.     public void saveToSDCard(String fileName, String content) throws IOException {  
  38.         //File file = new File(new File("/mnt/sdcard"),fileName);  
  39.         //考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录  
  40.         File file = new File(Environment.getExternalStorageDirectory(),fileName);  
  41.         FileOutputStream fileOutputStream = new FileOutputStream(file);  
  42.         fileOutputStream.write(content.getBytes());  
  43.         fileOutputStream.close();  
  44.     }  
  45.     /**  
  46.      * 读取文件内容  
  47.      * @param fileName 文件名称  
  48.      * @return 文件内容  
  49.      * @throws IOException  
  50.      */  
  51.     public String read(String fileName) throws IOException {  
  52.         FileInputStream fileInputStream = context.openFileInput(fileName);  
  53.         //把每次读取的内容写入到内存中,然后从内存中获取  
  54.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
  55.         byte[] buffer = new byte[1024];  
  56.         int len =0;  
  57.         //只要没读完,不断的读取  
  58.         while((len=fileInputStream.read(buffer))!=-1){  
  59.             outputStream.write(buffer, 0, len);  
  60.         }  
  61.         //得到内存中写入的所有数据  
  62.         byte[] data = outputStream.toByteArray();  
  63.         return new String(data);  
  64.     }  
  65. }  


FileService.java该类处理保存操作,使用FileOutPutStream输出流来写入数据到文件,在写入到系统内存时,我们可以直接用

context.openFileOutput(fileName, Context.MODE_WORLD_READABLE) 来快速获取一个文件输出流对象,这里我什么要把Context上下文对象写在构造方法里面呢,因为这样的话就是在new FileService对象时就传递上下文对象过来,避免遗漏的问题。

如果是写入到手机,我们就不能使用context.openFileOutput文件输出流对象了,因为它默认是保存数据到手机自带的空间下,我们使用
new File(Environment.getExternalStorageDirectory(),fileName); 因为不同的版本系统里面SDCard的目录可能不一样。


这里有个参数需要说明就是,文件的操作模式:

1、Context.MODE_PRIVATE:默认操作模式,代表该文件是私有文件,只能被该应用本身访问,并且采用覆盖式写入方式。

2、Context.MODE_APPEND:以追加模式来保存数据,该模式会检查文件是否存在,存在则追加内容,否则就创建文件。

3、Context.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取。

4、Context.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入(但是不能读取)。

如果希望文件可以被其他应用读和写,可以传入:Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE


AndroidManifest.xml
[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.file.activity"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.     <uses-sdk android:minSdkVersion="8" />  
  7.     <application  
  8.         android:icon="@drawable/ic_launcher"  
  9.         android:label="@string/app_name" >  
  10.         <activity  
  11.             android:label="@string/app_name"  
  12.             android:name=".MainActivity" >  
  13.             <intent-filter >  
  14.                 <action android:name="android.intent.action.MAIN" />  
  15.                 <category android:name="android.intent.category.LAUNCHER" />  
  16.             </intent-filter>  
  17.         </activity>  
  18.         <activity android:name=".FileReadActivity"/>  
  19.     </application>  
  20.     <!-- 在SD卡中创建和删除文件权限 -->  
  21.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
  22.     <!-- 往SD卡写入数据的权限 -->  
  23.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  24. </manifest>  

点击保存之后,我们可以在Eclipse的 File Explorer 中查看保存的文件,在data/data/[ packagename ]/wulianghuan





点击保存数据到SD卡按钮之后,我们可以在Eclipse的 File Explorer 中查看保存的文件,在mnt/sdcard/wulianghuan



点击读取数据之后,我们可以在新打开的Activity中显示数据

0 0
原创粉丝点击