Android学习笔记---android数据存储与访问数据存储与访问---------------------------------------一个在
Android学习笔记---android数据存储与访问
数据存储与访问---------------------------------------一个在手机和sd卡上存储文件的例子1.a.文件名称:lable b.一个text框 c.文件内容:label d.一个text框 e.保存:button-----------------------------/File/res/layoutpackage com.credream.file;
import com.credream.service.FileService;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;
public class FileActivity extends Activity{/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);setContentView(R.layout.main);Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new ButtonClickListener());
}
private final class ButtonClickListener implements View.OnClickListener{
@Overridepublic void onClick(View v){EditText
filenameText = (EditText) findViewById(R.id.filename);EditText
contentText = (EditText) findViewById(R.id.filecontent);
String filename = filenameText.getText().toString();String content = contentText.getText().toString();
FileService service = new FileService(getApplicationContext());
// 这里也可以传FileActivity,因为FileActivity类,也是继承自
// Context
try{service.save(filename, content);
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
} catch (Exception e){Toast.makeText(getApplicationContext(), R.string.fail, 1).show
();e.printStackTrace();}
}
}}-----------------------------------------/File/src/com/credream/service/FileService.javapackage com.credream.service;
import java.io.FileOutputStream;
import android.content.Context;
public class FileService{/** *保存文件 * @param filename 文件名称 * @param content 文件内容 */private Context context;public FileService(Context context){this.context = context;}public void save(String filename, String content) throws Exception{ //IO j2eeFileOutputStream outStream=context.openFileOutput
(filename,Context.MODE_PRIVATE);//mode:以覆盖形式和追加形式两种 //context.openFileOutput(filename,mode)//Context.MODE_PRIVATE私有操作模式 创建出来的文件只能被本应用访问
;其他应用无法访问该文件//另外采用私有操作模式创建的文件,写入文件中的内容覆盖源文件的内容outStream.write(content.getBytes());//content.getBytes()这个方法
调用系统的//Returns a new byte array containing the characters of this
string encoded using the system's default charset. //默认是用utf-8//The behavior when this string cannot be represented in the
system's default charset is unspecified. In practice, when the default charset is
UTF-8 (as it is on Android), all strings can be encoded. //没有默认编码的时候,会用iso8859-1来编码}}----------------------------openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文
件不存在,Android 会自动创建它。创建的文件保存在/data/data/<package name>/files目
录,如: /data/data/cn.itcast.action/files/itcast.txt ,通过点击Eclipse菜
单“Window”-“Show View”-“Other”,在对话窗口中展开android文件夹,选择下面的
File Explorer视图,然后在File Explorer视图中展开/data/data/<package name>/files目
录就可以看到该文件。openFileOutput()方法的第二参数用于指定操作模式,有四种模式,分别为:
Context.MODE_PRIVATE = 0Context.MODE_APPEND = 32768Context.MODE_WORLD_READABLE = 1Context.MODE_WORLD_WRITEABLE = 2Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,
在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可
以使用Context.MODE_APPENDContext.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文
件。Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权
限读写该文件。MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;MODE_WORLD_WRITEABLE:表示当
前文件可以被其他应用写入。如果希望文件被其他应用读和写,可以传入: openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE +
Context.MODE_WORLD_WRITEABLE);-------------------------------android有一套自己的安全模型,当应用程序(.apk)在安装时系统就会分配给他一个userid,
当该应用要去访问其他资源比如文件的时候,就需要userid匹配。默认情况下,任何应用创
建的文件,sharedpreferences,数据库都应该是私有的(位于/data/data/<package
name>/files),其他程序无法访问。除非在创建时指定了Context.MODE_WORLD_READABLE或
者Context.MODE_WORLD_WRITEABLE ,只有这样其他程序才能正确访问。----------------------------------1.数据的读取: 用数据的输入流----------------------在FileService.java中添加读取内容的方法/** * 文件读取内容 * @param filename 文件名 * @return * @throws Exception */public String read(String filename) throws Exception{FileInputStream inputStream=context.openFileInput(filename);ByteArrayOutputStream outputStream=new ByteArrayOutputStream();//这个方法会在/data/data/<package name>/files目录下查找这个文件//如果找到了就返回一个输入流byte[] buffer=new byte[1024];//inputStream.read(buffer);//读满这个数组后返回//只要数据没有读完,需要一直调用这个方法//这个方法的返回值为-1的时候,是读完了,不是-1的时候返回的是//读取的大小字节int len=0; while ((len=inputStream.read(buffer))!=-1){outputStream.write(buffer,0,len); //把读取的数据放到内存中 } byte[] data=outputStream.toByteArray(); return new String(data);}
---------------------------编写测试类:readTest.javapackage com.credream.file;
import com.credream.service.FileService;
import android.test.AndroidTestCase;import android.util.Log;
public class readTest extends AndroidTestCase{private static final String TAG="FileServiceTest";public void testRead()throws Exception{FileService service=new FileService(this.getContext());String result=service.read("lidewei.txt");Log.i(TAG, result);}}-------------------------AndroidManifest.xml清单文件中添加测试junit支持包<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.credream.file" 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=".FileActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-library android:name="android.test.runner" /> </application> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.credream.file" /></manifest>---------------------------右键测试,并用过滤器查看:03-05 00:31:17.771: I/FileServiceTest(7453):
www.credream.com