您的位置:首页 > 移动开发 > Android开发

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

2016-08-31 08:42 218 查看
版权所有: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?

<?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="@string/fileName" />  
    <EditText   
        android:id="@+id/filename"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"/>  
    <TextView  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="@string/content" />  
    <EditText   
        android:id="@+id/content"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"/>  
    <Button   
        android:id="@+id/save"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="@string/save"/>  
    <Button   
        android:id="@+id/saveToSdCard"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="@string/saveToSDCard"/>  
    <Button   
        android:id="@+id/read"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="@string/read"/>  
</LinearLayout>  

read.xml

[html]
view plain
copy
print?

<?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:id="@+id/filecontent"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"/>  
</LinearLayout>  

Strings.xml

[html]
view plain
copy
print?

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string name="hello">Hello World, MainActivity!</string>  
    <string name="app_name">文件存储应用</string>  
    <string name="fileName">文件名</string>  
    <string name="content">文件内容</string>  
    <string name="save">保存</string>  
    <string name="saveToSDCard">保存数据到SD卡</string>  
    <string name="read">读取数据</string>  
    <string name="fileSaveException">文件保存出现异常</string>  
    <string name="sdCardException">SD卡不存在,或者写保护</string>  
    <string name="fileSaveSuccess">文件保存成功</string>  
</resources>  

MainActivity.Java

[html]
view plain
copy
print?

package com.preferences.activity;  
  
import java.util.Map;  
  
import com.preferences.service.PreferencesService;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.EditText;  
import android.widget.Toast;  
  
public class MainActivity extends Activity {  
    private EditText name;  
    private EditText age;  
    private PreferencesService service;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        name = (EditText)findViewById(R.id.name);  
        age = (EditText)findViewById(R.id.age);  
        service = new PreferencesService(MainActivity.this);  
        //打开时读取保存的参数  
        Map<String,String> params = service.getPreferences();  
        name.setText(params.get("username"));  
        age.setText(params.get("age"));  
    }  
    public void save(View v){  
        String userName = name.getText().toString();  
        int userAge = Integer.parseInt(age.getText().toString());  
        service.save(userName, userAge);  
        Toast.makeText(MainActivity.this, "保存成功", 1).show();  
    }  
}  

FileReadActivity.java

[html]
view plain
copy
print?

package com.file.activity;  
  
import java.io.IOException;  
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.widget.TextView;  
import com.file.service.FileService;  
  
public class FileReadActivity extends Activity{  
    private TextView content;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.read);  
        content = (TextView)findViewById(R.id.filecontent);  
        FileService fileService =new FileService(getApplicationContext());  
        Intent intent = getIntent();  
        String fileName = intent.getStringExtra("fileName");  
        try {  
            content.setText(fileService.read(fileName));  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
      
}  

FileService.java

[html]
view plain
copy
print?

package com.file.service;  
  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import android.content.Context;  
import android.os.Environment;  
  
public class FileService {  
    private Context context;  
    public FileService(Context context) {  
        super();  
        this.context = context;  
    }  
    /**  
     * 保存文件  
     * @param fileName 文件名称  
     * @param content  文件内容  
     * @throws IOException  
     */  
    public void save(String fileName, String content) throws IOException {  
        //以私有方式读写数据,创建出来的文件只能被该应用访问  
        FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);  
        fileOutputStream.write(content.getBytes());  
        fileOutputStream.close();  
    }  
      
    /**  
     * 保存文件  
     * @param fileName 文件名称  
     * @param content  文件内容  
     * @throws IOException  
     */  
    public void saveToSDCard(String fileName, String content) throws IOException {  
        //File file = new File(new File("/mnt/sdcard"),fileName);  
        //考虑不同版本的sdCard目录不同,采用系统提供的API获取SD卡的目录  
        File file = new File(Environment.getExternalStorageDirectory(),fileName);  
        FileOutputStream fileOutputStream = new FileOutputStream(file);  
        fileOutputStream.write(content.getBytes());  
        fileOutputStream.close();  
    }  
    /**  
     * 读取文件内容  
     * @param fileName 文件名称  
     * @return 文件内容  
     * @throws IOException  
     */  
    public String read(String fileName) throws IOException {  
        FileInputStream fileInputStream = context.openFileInput(fileName);  
        //把每次读取的内容写入到内存中,然后从内存中获取  
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len =0;  
        //只要没读完,不断的读取  
        while((len=fileInputStream.read(buffer))!=-1){  
            outputStream.write(buffer, 0, len);  
        }  
        //得到内存中写入的所有数据  
        byte[] data = outputStream.toByteArray();  
        return new String(data);  
    }  
}  

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?

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="com.file.activity"  
    android:versionCode="1"  
    android:versionName="1.0" >  
    <uses-sdk android:minSdkVersion="8" />  
    <application  
        android:icon="@drawable/ic_launcher"  
        android:label="@string/app_name" >  
        <activity  
            android:label="@string/app_name"  
            android:name=".MainActivity" >  
            <intent-filter >  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
        <activity android:name=".FileReadActivity"/>  
    </application>  
    <!-- 在SD卡中创建和删除文件权限 -->  
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
    <!-- 往SD卡写入数据的权限 -->  
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
</manifest>  

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



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



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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐