⑴ 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