⑴ android文件存储方式,分类,利弊,什么时候使用
第一种: 使用SharedPreferences存储数据
适用范围:保存少量的数据,且这些数据的格式非常简单:字符串型、基本类型的值。比如应用程序的各种配置信息(如是否打开音效、是否使用震动效果、小游戏的玩家积分等),解锁口 令密码等
核心原理:保存基于XML文件存储的key-value键值对数据,通常用来存储一些简单的配置信息。通过DDMS的File Explorer面板,展开文件浏览树,很明显SharedPreferences数据总是存储在/data/data//shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过SharedPreferences.edit()获取的内部接口Editor对象实现。 SharedPreferences本身是一 个接口,程序无法直接创建SharedPreferences实例,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取SharedPreferences实例,该方法中name表示要操作的xml文件名,第二个参数具体如下:
Context.MODE_PRIVATE: 指定该SharedPreferences数据只能被本应用程序读、写。
Context.MODE_WORLD_READABLE: 指定该SharedPreferences数据能被其他应用程序读,但不能写。
Context.MODE_WORLD_WRITEABLE: 指定该SharedPreferences数据能被其他应用程序读,写
SharedPreferences对象与SQLite数据库相比,免去了创建数据库,创建表,写SQL语句等诸多操作,相对而言更加方便,简洁。但是SharedPreferences也有其自身缺陷,比如其职能存储boolean,int,float,long和String五种简单的数据类型,比如其无法进行条件查询等。所以不论SharedPreferences的数据存储操作是如何简单,它也只能是存储方式的一种补充,而无法完全替代如SQLite数据库这样的其他数据存储方式。
第二种: 文件存储数据
可以在设备本身的存储设备或者外接的存储设备中创建用于保存数据的文件。同样在默认的状态下,文件是不能在不同的程序间共享。
写文件:调用Context.openFileOutput()方法根据指定的路径和文件名来创建文件,这个方法会返回一个FileOutputStream对象。
读取文件:调用Context.openFileInput()方法通过制定的路径和文件名来返回一个标准的Java FileInputStream对象。
第三种:SQLite存储数据
SQLite Database数据库。Android对数据库的支持很好,它本身集成了SQLite数据库,每个应用都可以方便的使用它,或者更确切的说,Android完全依赖于SQLite数据库,它所有的系统数据和用到的结构化数据都存储在数据库中。 它具有以下优点: a. 效率出众,这是无可否认的 b. 十分适合存储结构化数据 c. 方便在不同的Activity,甚至不同的应用之间传递数据。
第四种:ContentProvider
Android系统中能实现所有应用程序共享的一种数据存储方式,由于数据通常在各应用间的是互相私密的,所以此存储方式较少使用,但是其又是必不可少的一种存储方式。例如音频,视频,图片和通讯录,一般都可以采用此种方式进行存储。每个ContentProvider都会对外提供一个公共的URI(包装成Uri对象),如果应用程序有数据需要共享时,就需要使用ContentProvider为这些数据定义一个URI,然后其他的应用程序就通过Content Provider传入这个URI来对数据进行操作。
总结一下,文件适用于存储一些简单的文本数据或者二进制数据,SharedPreferences适用于存储一些键值对,而数据库则适用于那些复杂的关系型数据。
⑵ Android界面中一个文本框,返回时保存数据,
先保存文本框内容
SharedPreferences sharedPreferences = getSharedPreferences("wenben", Context.MODE_PRIVATE); //私有数据
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("wenben", 文本框.gettext().toString);
editor.commit();//提交修改
再打开
文本框.settext(sharedPreferences.getString("wenben"));
⑶ Android写入txt文件
分以下几个步骤:
首先对manifest注册SD卡读写权限
AndroidManifest.xml
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="
package="com.tes.textsd"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.tes.textsd.FileOperateActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>创建一个对SD卡中文件读写的类
FileHelper.java
/**
*@Title:FileHelper.java
*@Packagecom.tes.textsd
*@Description:TODO(用一句话描述该文件做什么)
*@authorAlex.Z
*@date2013-2-26下午5:45:40
*@versionV1.0
*/
packagecom.tes.textsd;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.FileWriter;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importandroid.content.Context;
importandroid.os.Environment;
publicclassFileHelper{
privateContextcontext;
/**SD卡是否存在**/
privatebooleanhasSD=false;
/**SD卡的路径**/
privateStringSDPATH;
/**当前程序包的路径**/
privateStringFILESPATH;
publicFileHelper(Contextcontext){
this.context=context;
hasSD=Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
SDPATH=Environment.getExternalStorageDirectory().getPath();
FILESPATH=this.context.getFilesDir().getPath();
}
/**
*在SD卡上创建文件
*
*@throwsIOException
*/
publicFilecreateSDFile(StringfileName)throwsIOException{
Filefile=newFile(SDPATH+"//"+fileName);
if(!file.exists()){
file.createNewFile();
}
returnfile;
}
/**
*删除SD卡上的文件
*
*@paramfileName
*/
publicbooleandeleteSDFile(StringfileName){
Filefile=newFile(SDPATH+"//"+fileName);
if(file==null||!file.exists()||file.isDirectory())
returnfalse;
returnfile.delete();
}
/**
*写入内容到SD卡中的txt文本中
*str为内容
*/
publicvoidwriteSDFile(Stringstr,StringfileName)
{
try{
FileWriterfw=newFileWriter(SDPATH+"//"+fileName);
Filef=newFile(SDPATH+"//"+fileName);
fw.write(str);
FileOutputStreamos=newFileOutputStream(f);
DataOutputStreamout=newDataOutputStream(os);
out.writeShort(2);
out.writeUTF("");
System.out.println(out);
fw.flush();
fw.close();
System.out.println(fw);
}catch(Exceptione){
}
}
/**
*读取SD卡中文本文件
*
*@paramfileName
*@return
*/
publicStringreadSDFile(StringfileName){
StringBuffersb=newStringBuffer();
Filefile=newFile(SDPATH+"//"+fileName);
try{
FileInputStreamfis=newFileInputStream(file);
intc;
while((c=fis.read())!=-1){
sb.append((char)c);
}
fis.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnsb.toString();
}
publicStringgetFILESPATH(){
returnFILESPATH;
}
publicStringgetSDPATH(){
returnSDPATH;
}
publicbooleanhasSD(){
returnhasSD;
}
}写一个用于检测读写功能的的布局
main.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/hasSDTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"/>
<TextView
android:id="@+id/SDPathTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"/>
<TextView
android:id="@+id/FILESpathTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"/>
<TextView
android:id="@+id/createFileTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="false"/>
<TextView
android:id="@+id/readFileTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="false"/>
<TextView
android:id="@+id/deleteFileTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="false"/>
</LinearLayout>就是UI的类了
FileOperateActivity.class
/**
*@Title:FileOperateActivity.java
*@Packagecom.tes.textsd
*@Description:TODO(用一句话描述该文件做什么)
*@authorAlex.Z
*@date2013-2-26下午5:47:28
*@versionV1.0
*/
packagecom.tes.textsd;
importjava.io.IOException;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.widget.TextView;
{
privateTextViewhasSDTextView;
privateTextViewSDPathTextView;
;
;
;
;
privateFileHelperhelper;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
hasSDTextView=(TextView)findViewById(R.id.hasSDTextView);
SDPathTextView=(TextView)findViewById(R.id.SDPathTextView);
FILESpathTextView=(TextView)findViewById(R.id.FILESpathTextView);
createFileTextView=(TextView)findViewById(R.id.createFileTextView);
readFileTextView=(TextView)findViewById(R.id.readFileTextView);
deleteFileTextView=(TextView)findViewById(R.id.deleteFileTextView);
helper=newFileHelper(getApplicationContext());
hasSDTextView.setText("SD卡是否存在:"+helper.hasSD());
SDPathTextView.setText("SD卡路径:"+helper.getSDPATH());
FILESpathTextView.setText("包路径:"+helper.getFILESPATH());
try{
createFileTextView.setText("创建文件:"
+helper.createSDFile("test.txt").getAbsolutePath());
}catch(IOExceptione){
e.printStackTrace();
}
deleteFileTextView.setText("删除文件是否成功:"
+helper.deleteSDFile("xx.txt"));
helper.writeSDFile("1213212","test.txt");
readFileTextView.setText("读取文件:"+helper.readSDFile("test.txt"));
}
}
⑷ android怎么将一个文本文件写入pc机
Android 怎样在应用程序中向文件里写入数据?在AndroidManifestmit(); 获取 :sp =getPreferences(MODE_PRIVATE); String result =spmit(); } } Files从这是第二种方法,可以在设备本身的存储设备或者外接的存储设备中创建用于保存数据的文件。同样在默认的状态下,文件是不能在不同的程序间共享。写文件:调用Context.openFileOutput()方法根据指定的路径和文件名来创建文件,这个方法会返回一个FileOutputStream对象。读取文件:调用Context.openFileInput()方法通过制定的路径和文件名来返回一个标准的Java FileInputStream对象。 (注意:在其它程序中将无法应用相同的路径和文件名来操作文件)另外编译程序之前,在res/raw/tempFile中建立一个static文件,这样可以在程序中通过Resources.openRawResource (R.raw.myDataFile)方法同样返回一个InputStream对象,直接读取文件内容。Databases在Android API中包括了应用SQLite databases的接口,每个程序所创建的数据库都是私有的,换句话说,程序间无法相互访问对方的数据库。在程序中创建SQLiteDatabase对象,其中包含了大部分与database交互的方法,例如:读取数据或者管理当前数据。可以应用SQLiteDatabase和其subClassSQLiteOpenHelper的create()方法来创建新的数据库。对于SQLitedatabase而言,其强大和方便的功能为Android提供了强有力的存储功能。特别是存储一些复杂的数据结构,例如:Android特别为通讯录创建了特有的数据类型,其中包含了非常多的子集而且涵盖了大部分的数据类型 “First Name” “Last Name” “PhoneNumber”和“Photo”等。Android可以通过Sqlite3 database tool来查看指定数据库中表的内容,直接运行SQL命令来快速便捷的直接操作SQLite database。
⑸ 求一个简单存储android数据的java代码,就是将一个数据存入一个txt文件即可
//添加文件写入和创建的权限
Stringaaa=Environment.getExternalStorageDirectory()
+File.separator+"aaa.txt";
Filefile=newFile(aaa);
try{
if(!file.exists()){
file.createNewFile();
}
FileWriterpw=newFileWriter(file,true);
pw.write(aaa);
pw.flush();
pw.close();
}catch(IOExceptione){
e.printStackTrace();
}
⑹ Android 文件存储 本人Android新手,想做一个记事本,对于文本的存储,大神们给点意见
创建文件不是好的解决方案,如果有一百个笔记,岂不是要创建100个文件? 记事本采用SQLite存储吧,android系统自带的轻量级数据库。 一个笔记有标题和日期 还有内容主体,只需要在数据表建立三个字段,每新建一个笔记就插入一条记录。
⑺ Android怎么把处理的结果保存到文件中
我刚才特意试了一下在自己的代码里加了点调试信息
String user = _loginUser.getText().toString();
int firstCR = user.indexOf("\n");
_loginUser是我UI中的EditText,在其中我输入了3行文字,每行文字我都是手动按回车键换行,这样取出来的文本是带有换行符的。
但是你如果是一直输入满后让EditText自动换行的话,这样取出来是不带换行符的。这样其实是很有道理的,自动换行本来就不会给你插入换行符,它只是由于UI的边界,看起来像换行了一样。
我觉得有种简便办法可以解决。
int lineCount = _loginUser.getLineCount();
这样可以取得EditTex里的行数
把它和里面找到的'\n'比较一下数量,就知道你的这段文本大概是个什么情况。
1 如果行数和\n数量对得上,说明每行都是手工回车换行的这种最简单,直接保存。
2 如果\n为0说明都是ui自动换行的,这样也简单,把总字数和行数一计算就知道有多少行,每行多少字,然后自己存盘时插入换行符。当然这样不太准确,算是折中。
3 对不上,说明有自动换行,也有手动换行,这种其实很麻烦,可以参考2的办法解决了。
总之没有太好的办法,毕竟EditText没法按行数取得文本
你可以自己覆写一个EditText的子类,来提供这样的方法。
⑻ android中想要对文本框中输入的数据进行保存怎么实现
Android应用开发中,给我们提供了5种数据的存储方式
1 使用SharedPreferences存储数据
2 文件存储数据
3 SQLite数据库存储数据
4 使用ContentProvider存储数据
5 网络存储数据
不同的业务逻辑,或者需求,用不同的实现方式,以下是这几中数据存储方式的说明用及法:
第一种: 使用SharedPreferences存储数据
SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存。
以下为示例代码:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取SharedPreferences对象
Context ctx = MainActivity.this;
SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
//存入数据
Editor editor = sp.edit();
editor.putString("STRING_KEY", "string");
editor.putInt("INT_KEY", 0);
editor.putBoolean("BOOLEAN_KEY", true);
editor.commit();
//返回STRING_KEY的值
Log.d("SP", sp.getString("STRING_KEY", "none"));
//如果NOT_EXIST不存在,则返回值为"none"
Log.d("SP", sp.getString("NOT_EXIST", "none"));
}
}
第二种: 文件存储数据
关于文件存储,Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的。
文件可用来存放大量数据,如文本、图片、音频等。
默认位置:/data/data/< >/files/***.***。
代码示例:
public void save(){
try {
FileOutputStream outStream=this.openFileOutput("a.txt",Context.MODE_WORLD_READABLE);
outStream.write(text.getText().toString().getBytes());
outStream.close();
Toast.makeText(MyActivity.this,"Saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
return;
}
catch (IOException e){
return ;
}
}
第三种: SQLite数据库存储数据
SQLite是轻量级嵌入式数据库引擎,它支持 SQL 语言,并且只利用很少的内存就有很好的性能。此外它还是开源的,任何人都可以使用它。许多开源项目((Mozilla, PHP, Python)都使用了 SQLite。
SQLite 由以下几个组件组成:SQL 编译器、内核、后端以及附件。
SQLite 通过利用虚拟机和虚拟数据库引擎(VDBE),使调试、修改和扩展 SQLite 的内核变得更加方便。
读取文件示例:
public void load(){
try {
FileInputStream inStream=this.openFileInput("a.txt");
ByteArrayOutputStream stream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int length=-1;
while((length=inStream.read(buffer))!=-1) {
stream.write(buffer,0,length);
}
stream.close();
inStream.close();
text.setText(stream.toString());
Toast.makeText(MyActivity.this,"Loaded",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
return ;
}
}
第四种 使用ContentProvider存储数据 ContentProvider其实也是通过数据库的方式来存储数据的,因此这里不再做详细介绍
第五种 网络存储数据 也就是说将数据保存在服务器,android上只需要通过httpclient发起一个请求,向服务器获取数据即可
⑼ 简述Android中如何利用文件存储来读写SD卡上的TXT文件。
确定这么做就必须要意识到一旦放进去就成死的了。而且你说的“改一下”更好的方法是“扩展一下” 扩展下你的电纸书包含一些默认的文件。
⑽ Android本地存储的几种方式
Android 提供了5种方式存储数据: --使用SharedPreferences存储数据; --文件存储数据; --SQLite数据库存储数据; --使用ContentProvider存储数据; --网络存储数据; 先说下,Preference,File, DataBase这三种方式分别对应的目录是/data/data/Package Name/Shared_Pref, /data/data/Package Name/files, /data/data/Package Name/database 。 在Android中通常使用File存储方式是用 Context.openFileOutput(String fileName, int mode)和Context.openFileInput(String fileName)。 Context.openFileOutput(String fileName, int mode)生成的文件自动存储在/data/data/Package Name/files目录下,其全路径是/data/data/Pac