Android数据存储之内部文件存储(一)

来源:互联网 发布:大宗商品进出口数据 编辑:程序博客网 时间:2024/04/29 02:57

我们可以直接保存一个文件到内部设备的存储,这个文件默认的保存在内部存储的应用是私有的,其他应用是永远访问不到的。当用户卸载这个app应用的时候,这些文件都会被卸载掉。

文件以.txt的格式被保存

保证程序运行的效率,第一次取下来的图片,我们把它保存在本地,下次再运行同样的界面就不需要在网络上取图片了,只需要在本地把图片提取出来,这样就实现了缓存的操作(这种叫硬件缓存)。主要是使用手机的存储能力作为缓存。

创建一个私有的内部文件步骤:

①调用openFileOutput()

②往文件里面写用write()

③close()

创建工程Android_data_InteralStorage,添加单元测试

在AndroidManifest.xml中单击Instrumentation->Add->双击Instrumentation->Name Browse 选中android.test.InstrumentationTestRunner->Target Packet Browse 选中自己的工程名的包->点击AndroidManifest,在application节点里面添加 <uses-library android:name="android.test.runner"/>

创建包com.example.android_data_interalstorage.file中新建一个类FileSave.java

package com.example.android_data_interalstorage.file;import java.io.FileOutputStream;import android.content.Context;public class FileSave {private Context context;public FileSave() {// TODO Auto-generated constructor stubthis.context=context;}/** *  * @param fileName * @param mode * @param data * @return */public boolean saveContentToFile(String fileName,int mode, byte[] data){boolean flag=true;FileOutputStream outputStream = null;try {outputStream = context.openFileOutput(fileName, mode);outputStream.write(data, 0, data.length);flag = true;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (Exception e2) {// TODO: handle exception}}}return flag;}}

在com.example.android_data_interalstorage下创建单元测试MyTest.java

package com.example.android_data_interalstorage;import com.example.android_data_interalstorage.file.FileSave;import android.content.Context;import android.test.AndroidTestCase;import android.util.Log;public class MyTest extends AndroidTestCase {private final String TAG = "MyTest";public void save() {FileSave fileSave = new FileSave(getContext());//操作文件的模式:private 私有模式 追加 append//MODE_WORLD_READABLE 可读//MODE_WORLD_WRITEABLE 可写//文件必须加后缀名aa.txt,xml的不需要加后缀名boolean flag = fileSave.saveContentToFile("aa.txt",Context.MODE_PRIVATE, "第一次创建".getBytes());Log.i(TAG, "--->>" + flag);}}
双击save()进行单元测试


做个小例子:做一个界面,点击保存信息,把编辑框的数据保存在文件里(.txt)

在activity_main.xml中添加代码

    <EditText        android:id="@+id/editText1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_alignParentTop="true"        android:layout_marginTop="18dp"        android:ems="10" >    </EditText>    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/editText1"        android:layout_centerHorizontal="true"        android:layout_marginTop="49dp"        android:text="保存信息" />

在MainActivity.java中

package com.example.android_data_interalstorage;import com.example.android_data_interalstorage.file.FileSave;import android.support.v7.app.ActionBarActivity;import android.content.Context;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends ActionBarActivity {private EditText editText;private Button button;private FileSave fileSave=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);fileSave=new FileSave(this);editText=(EditText) this.findViewById(R.id.editText1);button=(Button) this.findViewById(R.id.button1);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString value=editText.getText().toString().trim();boolean flag=fileSave.saveContentToFile("login.txt", Context.MODE_APPEND, value.getBytes());if(flag){Toast.makeText(MainActivity.this, "保存文件成功", 1).show();}}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}

运行效果(不是测试)如下

再输入123ccnu继续保存则在login.txt中数据

因为是追加形式Context.MODE_APPEND,可以直接追加在文件数据后面。




接下来,读取文件

FileSave.java中

package com.example.android_data_interalstorage.file;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import android.content.Context;public class FileSave {private Context context;public FileSave(Context context) {// TODO Auto-generated constructor stubthis.context=context;}/**读文件 *  * 一般在IO流中要有盘符路径,但是在Android开发中没有盘符的概念,因为Android开发是基于linux的开发 * @param fileName * @return */public String readContentFromFile(String fileName) {FileInputStream fileInputStream = null;ByteArrayOutputStream outputStream = new ByteArrayOutputStream();try {fileInputStream = context.openFileInput(fileName);int len = 0;byte[] data = new byte[1024];while((len = fileInputStream.read(data))!=-1){outputStream.write(data, 0, len);}return new String(outputStream.toByteArray());} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return "";}/** *  * @param fileName * @param mode * @param data * @return */public boolean saveContentToFile(String fileName,int mode, byte[] data){boolean flag=true;FileOutputStream outputStream = null;try {outputStream = context.openFileOutput(fileName, mode);outputStream.write(data, 0, data.length);flag = true;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();} finally {if (outputStream != null) {try {outputStream.close();} catch (Exception e2) {// TODO: handle exception}}}return flag;}}

在MyTest.java中添加单元测试代码

public void read(){FileSave service = new FileSave(getContext());String msg = service.readContentFromFile("login.txt");Log.i(TAG, "--->>" + msg);}



0 0
原创粉丝点击