android学习笔记6--------------数据的存储与访问(1)

转载注明出处:袁方的技术博客 http://blog.csdn.net/yf210yf

android为数据存储提供了多种方式:

1.文件

2.SharedPreferences    (主要存储软件的配置参数)

3.SQLite数据库

4.内容提供者(content provider)(对外共享数据时使用)

5.网络

    首先看对文件的操作,实现的要求:

1.指定保存的文件类型

2.指定保存的文件文本信息

3.读取指定的文件内容

一、业务bean

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileService
{
	/**
	 * 保存数据
	 * 
	 * @param stream
	 * @param content
	 * @throws IOException
	 */
	public static void save(OutputStream stream, String content)
			throws IOException
	{
		stream.write(content.getBytes());
		stream.close();
	}

	/**
	 * 读取数据
	 * 
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static String read(InputStream inStream) throws IOException
	{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = -1;
		byte[] buffer = new byte[1024];
		while ((len = inStream.read(buffer)) != -1)
		{
			outputStream.write(buffer, 0, len);
		}
		byte[] data = outputStream.toByteArray();
		inStream.close();
		outputStream.close();
		return new String(data);

	}

}


二、单元测试

import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;

import com.luku.file.service.FileService;

public class FileServiceTest extends AndroidTestCase
{
	private static final String TAG = "FileServiceTest";

	/**
	 * 保存测试单元
	 * 保存在/data/data/包名/files下
	 * 
	 * @throws Exception
	 */
	public void testSave() throws Exception
	{
		
		OutputStream stream = this.getContext().openFileOutput("123.txt",//文件名称为123.txt
				Context.MODE_PRIVATE);
		FileService.save(stream, "你好");  //文件内容
	}
	
	/**
	 * 读取测试单元
	 * @throws Exception
	 */
	public void testRead() throws Exception
	{
		InputStream instream = this.getContext().openFileInput("123.txt");
		String string = FileService.read(instream);
		Log.i(TAG, string);
	}
}


补充:

openFileOutput第二个参数有四种模式,用于控制访问权限,分别为:

1.Context.MODE_PRIVATE =0                           只能被创建文件的应用程序读写,同名覆盖

2.Context.MODE_APPEND =32768                   只能被创建文件的应用程序读写,同名追加内容

3.Context.MODE_WORLD_READEBLE =1      能被其他应用程序读取

4.Context.MODE_WORLD_WRITEABLE =2     能被其他应用程序写入


执行测试单元后可以看到:(前提配置好测试单元)



将123.txt传到桌面

打开可以看到


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值