`

android的数据存储和访问 附源码

阅读更多
android提供了几种文件的存储方式;
1.文件:
2.SharedPreferences存储类似软件的配置参数设置的内容;这是一个类;
3.sqlite数据库 android内嵌的数据库,和微软的excel数据库原理一样,当你创建一个数据库时是以文件的形式存放的;sql语句很类似的;
4.网络
5.content provider
/////////////////////////////////////////
我们使用mvc模式开发一个保存文件内容的程序,我们在j2ee的时候是面向接口编程,可以降低耦合,在android中还是尽量避免使用太多的类,一是效率 二是手机内存不大,内部类是个不错的选择
先写业务层DataManager.java
package cn.lee.Manager;

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

public class DataManager {
	/**
	 * 没有使用成员变量的方法可以定义为静态方法
	 * 保存数据的业务逻辑
	 * OutputStream 输出流
	 * content 文件内容
	 * @throws Exception 
	 */
	public static void saveDate (OutputStream outputStream , String contentString) throws Exception
	{
		outputStream.write(contentString.getBytes());
		outputStream.close();
	}
	/**
	 * 读取数据的业务逻辑
	 * @param InputStream
	 * @param contentString
	 * @throws Exception
	 */
	public static  String readDate (InputStream inputStream ) throws Exception
	{
		byte [] byte1 = new byte[1024];
		/**
		 * 当输入流读到文件的末尾 返回就是-1 
		 */
		int length = inputStream.read(byte1);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		if(length!=-1)
		{
			//读到的内容存在内存中ByteArrayOutputStream 这个类用于将byte流存储在内存中
			
			byteArrayOutputStream.write(byte1, 0, length);
		}
		String dateString =   byteArrayOutputStream.toString();
		byteArrayOutputStream.close();
		inputStream.close();
		return dateString;
	}
}


再来测试这个业务层DateManagerTest .java
package cn.lee.data;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import cn.lee.Manager.DataManager;
import android.content.Context;
import android.test.AndroidTestCase;
import android.util.Log;

public class DateManagerTest extends AndroidTestCase {
	
	private static final String TAG="DateManagerTest";
	public void testSave ()throws Exception {
		/**
		 * 内容先定义成固定的内容
		 *  Activity的父类的父类就是context,context与其他框架中的context相同为我们以供了一些核心操作工具。
		 *  openFileOutput("fileName", Context.MODE_PRIVATE);
		 *  参数1:文件的名字 不能包含路径分隔符‘/’ 
		 *  使用这个方法创建的文件,会保存在手机/date/date/应用文件夹(这里就是cn.lee.data)/files目录下;
		 *  /date/date/cn.lee.data/files/fileName.txt 我们可以在window-show view -other-android-file explore看到
		 *  这是有android决定的;
		 *  参数2:保存的模式:  
		 *  使用context中的文件输出流它有四种模式:
		 *  文件读写的操作模式:
		 *      Context.MODE_PRIVATE=0:只能是当前的应用才能操作文件 如果创建的文件已经存在 新内容覆盖原内容
		 *      Context.MODE_APPEND=32768:新内容追加到原内容后 这个模式也是私有的 这个文件只能被创建文件的应用所访问
		 *      Context.MODE_WORLD_READABLE=1:允许其他应用程序读取本应用创建的文件
		 *      Context.MODE_WORLD_WRITEABLE=2:允许其他应用程序写入本应用程序创建的文件,会覆盖原数据。       		
		 */
		

        FileOutputStream fileOutputStream = this.getContext().openFileOutput("fileName.txt", Context.MODE_PRIVATE);
		DataManager.saveDate(fileOutputStream, "xxxxxxx");
	}
	public void  testRead() throws Exception{
		FileInputStream fileInputStream = this.getContext().openFileInput("fileName.txt");
		String contentString = DataManager.readDate(fileInputStream);
		Log.i(TAG, contentString);
	}
}


设计界面main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
		android:orientation="vertical" android:layout_width="fill_parent"
		android:layout_height="wrap_content">
		<TextView android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:text="@string/hello"
			android:id="@+id/filenameTesxwiew" />
		<EditText android:layout_width="60px"
			android:layout_toRightOf="@id/filenameTesxwiew"
			android:layout_alignTop="@id/filenameTesxwiew" android:layout_height="wrap_content"
			android:id="@+id/fileName" />
	</RelativeLayout>
	<TextView 
	android:layout_width="fill_parent"
	android:layout_height="wrap_content" 
	android:text="@string/contentlable" />
	<EditText
	android:layout_width="fill_parent"
	android:layout_height="wrap_content" 
	android:minLines="5"
	android:id="@+id/fileContent" />
	<Button 
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="@string/buttontext" 
	/>
</LinearLayout>

设计activity AboutDateActivity.java
package cn.lee.data;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.lee.Manager.DataManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AboutDateActivity extends Activity {
	private EditText fileNameEditText;
	private EditText fileContentEditText;
	private Button button;
	private static final String TAGSTRING ="AboutDateActivity";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		fileNameEditText = (EditText) this.findViewById(R.id.fileName);
		fileContentEditText = (EditText) this.findViewById(R.id.fileContent);
		button = (Button) this.findViewById(R.id.button);

		button.setOnClickListener(new OnClickListener() {
		
			public void onClick(View v) {
				int info = R.string.sus;
				String fileNameString = fileNameEditText.getText().toString();
				String fileContentString = fileContentEditText.getText()
						.toString();
				// TODO Auto-generated method stub
				FileOutputStream fileOutputStream = null;
				try {
					fileOutputStream = AboutDateActivity.this
							.openFileOutput(fileNameString, Context.MODE_PRIVATE);
					DataManager.saveDate(fileOutputStream, fileContentString);
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.i(TAGSTRING, e.toString());
					info = R.string.infor;
				}finally{
					try {
						fileOutputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						Log.i(TAGSTRING, e.toString());
						info = R.string.infor;
					}
				}
				Toast.makeText(AboutDateActivity.this, info, 1).show();
			}

		});
	}
}

你试试。
1
0
分享到:
评论
1 楼 struts_2010 2011-07-01  
感谢!

相关推荐

    Android数据存储和访问实验报告

    1.掌握SharedPreferences的使用方法; 2.掌握各种文件存储的区别与适用情况; 3.了解SQLite数据库的特点和体系结构;...源码和整个工程会上传到博客中,若有需要可下载。 该实验报告包含部分源码,和内容介绍。

    Android数据存储与访问(含源码加文档)

    1、练习使用SharedPreferences方式进行数据存储和访问 2、练习使用SQLite数据库的方式进行数据存储和访问 三、实验原理 数据存储方式,SharedPreferences,SQLite。 四、实验步骤及关键技术 一.本项目包含以下四个...

    android数据的存储与访问(数据保存mvc实现&访问权限源码

    android 根据教程自己敲得代码 这个懒了下没做注释 得自己去弄明白

    android的数据存储和访问 附

    NULL 博文链接:https://leequer.iteye.com/blog/607079

    Android基础 布局、数据存储访问、XML系列化解析和SharedPreferences入门

    3、数据存储与访问 主要介绍存储文件到外部存储器和内部存储器,利用系统提供的API获取路径时,需要精准的掌握他们的目录层级。在将数据保存到SDCard时,需要判断剩余存储空间。 SharedPreferences存储对于简单的...

    Android移动平台开发-数据存储应用.doc

    Android移动平台开发-实验报告

    Android在线教育app源码

    数据加密,内容云端存储,防盗防录屏,IP访问监控,全方位保护课程版权。 3、多终端支持 支持Web、Android、iOS、ipad等多个终端切换。 4、注重体验 高清视频直播授课,码率自适应,播放超低延迟,互动连麦流畅不...

    疯狂Android讲义源码

     第8章 Android的数据存储和IO 306  8.1 使用SharedPreferences 307  8.1.1 SharedPreferences与Editor  简介 307  8.1.2 SharedPreferences的存储  位置和格式 308  8.1.3 读、写其他应用Shared  ...

    深入浅出Android软件开发教程.pdf+源码

    讲解Android系统的体系结构、Java语言与面向对象编程基础、XML基础、开发环境搭建、Android应用程序的调试和发布方法、用户界面设计、组件间的通信与广播、后台服务、数据的存储和访问、图片和音视频的处理、Web应用...

    Android应用源码带PM2.5数据的知雨天气

    本应用是一个基于安卓的带有PM2.5数据的天气预报源码,天气数据是直接访问的http://m.weather.com.cn/data/xxxxxxxxxx.html,xxxxxxx需要替换成城市代码,例如北京是101010100。获取到天气的json数据后把所有数据...

    Android学习09-----Android中数据的存储和访问 (3) By SQLite

    NULL 博文链接:https://xdwangiflytek.iteye.com/blog/1401596

    Android项目源码NBA资讯和赛事信息的平台带服务端.zip

    全面、方便、快捷的获取新闻动态、比赛数据。 无广告、推送信息,不后台常驻,空间占用小。但是因为某些原因作者关闭了web服务器,因此项目无法直接演示了,不过有服务端,如果可以搞定的话可以自己搭建服务端做...

    Google Android SDK开发范例大全(完整版附部分源码).pdf

    包含部分书中源码 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1 安装AndroidSDK与ADTplug...

    Android-QQ-课程设计(源码+论文)

    源码分Eclipse和Android Studio两个版本 项目简介: Web服务器采用struts2、hibernate、spring框架,使用Mysql数据库存储数据。 在Android中 调用 URL进行后台访问靠JSON传值,进行仿QQ的一个开发,完成聊天,好友,...

    彩票app源码体彩体育赛事双端app原生运营源码.zip

    ,原代码开源,原生android+ios,所涉及彩种几十种,可自由匹配接口,源码开源:后端JAVA,前端源码,Android源码,IOS源码,数据库,Java爬虫采集,搭建教程等。 竞彩足球,竞彩篮球,北京单场,排列3,排列5… 爬虫(Web ...

    《Android应用开发揭秘》源码.rar

     本书内容全面,不仅详细讲解了android框架、android组件、用户界面开发、游戏开发、数据存储、多媒体开发和网络开发等基础知识,而且还深入阐述了传感器、语音识别、桌面组件开发、android游戏引擎设计、android...

    android访问网络get post 源代码项目

    保存登錄后的信息(如用戶名和密碼,可以自己設置) // 5.具有超级完整详细的注释(新手也能看懂) //可以设置成自己的UI库 // 注意: //1.需要设置androidManifest文件 // &lt;activity android:name=".IndexPage" ...

    Android开发案例驱动教程 配套代码

    10.2 Android数据存储概述 205 10.3 本地文件 205 10.3.1 访问SD卡 207 10.3.2 访问应用文件目录 212 10.4 SQLite数据库 216 10.4.1 SQLite数据类型 216 10.4.2 Android平台下管理SQLite数据库 216 10.5 编写...

    Android高级编程--源代码

    1.5.4 SQLite 数据存储和检索数据库 6 1.5.5 共享数据和应用程序间通信 7 1.5.6 使用Google Talk的P2P服务 7 1.5.7 扩展的数据支持和2D/3D图形 7 1.5.8 优化的内存和进程管理 8 1.6 开放手机联盟简介 8 1.7 ...

    JAVA上百实例源码以及开源项目源代码

     Java生成密钥、保存密钥的实例源码,通过本源码可以了解到Java如何产生单钥加密的密钥(myKey)、产生双钥的密钥对(keyPair)、如何保存公钥的字节数组、保存私钥到文件privateKey.dat、如何用Java对象序列化保存私钥...

Global site tag (gtag.js) - Google Analytics