文件存儲數據是指在Android系統中,直接把數據以文件的形式存儲在設備中。Android系統提供了openFileOutput(String name,int mode):第一個參數是用于指定文件名稱,第二個參數是用于指定文件存儲的方式。如果文件不存在,Android系統會為我們自動的創建它,創建的文件被保存在/data/data/<package name>/files目錄下的。
第二個參數也就是文件的打開方式有:
MODE_PRIVATE:默認打開方式,表示文件是私有數據,在默認模式下,只能被本身的應用訪問,在默認模式下,新寫入內容會覆蓋原文件的內容。
MODE_APPEND:該模式會先檢查數據文件是否存在,如果存在就在該數據文件內容基礎上追加新的內容,否則就創建新數據文件。
MODE_WORLD_READABLE:該模式下數據文件可以其他應用讀取。
MODE_WORLD_WRITEABLE:該模式下數據文件可以被其他應用讀取與寫入。
Context提供的幾個重要方法:
getDir(String name,int mode):在應用程序的數據文件下獲取或者創建name對應的子目錄。
File getFilesDir:獲取應用程序數據文件的絕對路徑。
String[] fileList():返回應用程序數據文件夾的全部文件。
下面附帶一個簡單的栗子:
先看布局:
代碼:
private EditText keyword;
private Button set_keyword;
private Button get_keyword;
private Button getDir;
private Button getFilesDir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
keyword= (EditText) findViewById(R.id.keyword);
set_keyword= (Button) findViewById(R.id.set_keyword);
get_keyword= (Button) findViewById(R.id.get_keyword);
set_keyword.setOnClickListener(this);
get_keyword.setOnClickListener(this);
getDir= (Button) findViewById(R.id.getDir);
getFilesDir= (Button) findViewById(R.id.getFilesDir);
getDir.setOnClickListener(this);
getFilesDir.setOnClickListener(this);
}
@Override
public voidonClick(View v) {
switch(v.getId()){
caseR.id.set_keyword:
writeKeyworld(keyword.getText().toString());
Toast.makeText(MainActivity.this,"文件存儲成功!",Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,"文件的路徑:"+getFilesDir(),Toast.LENGTH_SHORT).show();
break;
caseR.id.get_keyword:
Toast.makeText(MainActivity.this,readKeyworld().toString()+"",Toast.LENGTH_SHORT).show();
break;
caseR.id.getDir:
//在數據文件的目錄下獲取或者創建HelloAndroid的子目錄(在HellAndroid目錄不存在的時候)
Toast.makeText(MainActivity.this,"getDir:"+MainActivity.this.getDir("HelloAndroids", Context.MODE_PRIVATE),Toast.LENGTH_SHORT).show();
break;
caseR.id.getFilesDir:
//數據文件絕對路徑
Toast.makeText(MainActivity.this,"getFilesDir:"+MainActivity.this.getFilesDir,Toast.LENGTH_SHORT).show();
break;
}
}
//使用openFileOutput指定打開指定文件,并指定寫入模式
private voidwriteKeyworld(String msg) {
if(msg==""){
return;
}
try{
//通過openFileOutput拿到io流的FileOutputString對象
FileOutputStream fos=this.openFileOutput("message.txt",MODE_APPEND);
fos.write(msg.getBytes());
fos.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
//使用openFileInput打開指定文件
privateString readKeyworld() {
String data="";
try{
FileInputStream fis=this.openFileInput("message.txt");
byte[] buffer=new byte[1024];
inthasRead=0;
StringBuilder sb=newStringBuilder();
while((hasRead=fis.read(buffer))!=-1){
sb.append(newString(buffer,0,hasRead));
}
data=sb.toString();
fis.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
returndata;
}
運行結果:
上面這個栗子只包括android文件存儲的使用內置內存存儲。那么問題來,怎么把數據存儲在sd卡里邊呢?下片博文說吧。