Android入門:File檔案儲存體

來源:互聯網
上載者:User
文章目錄
  • 1.
  • 步驟1:設定模擬器支援sdcard
  • 步驟2:在應用中設定許可權
  • 注意:
  • 建議:

資料的儲存有多種方式,比如資料庫儲存、SharedPreferences儲存、檔案儲存體等;

這裡我們將要介紹最簡單的檔案儲存體方式;

檔案儲存體簡單的來說就是一般的JAVASE中的IO流,只是把他應用於Android手機中而已;

一、檔案儲存體核心代碼

檔案儲存體


(1)FileOutputStream out = context.openFileOutput(String filename,int mode); 以mode模式獲得檔案輸出資料流

(2)out.write(byte[]b);

FileOutputStream out = null;out = context.openFileOutput(filename, Context.MODE_***);out.write(filecontent.getBytes("UTF-8"));out.close();

注意:檔案預設會儲存到/data/data/package/files中;

檔案讀取


(1)FileInputStream in = context.openFileInput(String filename);   獲得某個檔案的檔案流

(2)int length = in.read(byte[]);

/*每次讀取固定的位元組,並將此位元組輸出到位元組輸出資料流中,當全部讀取完畢後,將位元組流中的內容一併輸出*/FileInputStream in = null;ByteArrayOutputStream bout = null;byte[]buf = new byte[1024];bout = new ByteArrayOutputStream();int length = 0;in = context.openFileInput(filename); //獲得輸入資料流while((length=in.read(buf))!=-1){bout.write(buf,0,length);}byte[] content = bout.toByteArray();filecontentEt.setText(new String(content,"UTF-8")); //設定文字框為讀取的內容in.close();bout.close();

注意:預設會讀取/data/data/package/files的檔案;

二、檔案模式介紹

1.Context.MODE_PRIVATE:私人覆蓋模式    
-  rw-  rw-  ---

只能被當前應用訪問,並且如果寫入,則覆蓋;

2.Context.MODE_APPEND:私人追加模式    
-   rw-  rw-  ---

只能被當前應用訪問,並且如果寫入,則追加;

3.Context,MODE_WORLD_READABLE:公有唯讀模式      -  rw-  rw-   r--

可以被其他應用讀取;

4.Context.MODE_WORLD_WRITEABLE:公有可寫入模式     - rw-   rw-  -w-

可以被其他應用寫入,但不能讀取;

注意,如果希望其他使得檔案模式疊加,則可以使用加號串連;

比如:Context.MODE_WORLD_READABLE Context.MODE_WORLD_WRITEABLE 表示其他應用讀寫;

三、簡單應用執行個體1.

目標:當點擊儲存時,將以特定的檔案名稱和特定的檔案內容儲存內容,點擊讀取時,將讀取特定的檔案的檔案內容顯示到檔案內容文字框;

當點擊儲存之後,效果如下:

MainActivity.java

package org.xiazdong.file;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {private Button saveButton,readButton;private EditText filenameEt,filecontentEt;private Context context = this;private OnClickListener listener = new OnClickListener(){@Overridepublic void onClick(View v) {if(v==saveButton){String filename = filenameEt.getText().toString();String filecontent = filecontentEt.getText().toString();FileOutputStream out = null;try {out = context.openFileOutput(filename, Context.MODE_PRIVATE);out.write(filecontent.getBytes("UTF-8"));} catch (Exception e) {e.printStackTrace();}finally{try {out.close();} catch (Exception e) {e.printStackTrace();}}}else if(v==readButton){String filename = filenameEt.getText().toString(); //獲得讀取的檔案的名稱FileInputStream in = null;ByteArrayOutputStream bout = null;byte[]buf = new byte[1024];bout = new ByteArrayOutputStream();int length = 0;try {in = context.openFileInput(filename); //獲得輸入資料流while((length=in.read(buf))!=-1){bout.write(buf,0,length);}byte[] content = bout.toByteArray();filecontentEt.setText(new String(content,"UTF-8")); //設定文字框為讀取的內容} catch (Exception e) {e.printStackTrace();}filecontentEt.invalidate(); //重新整理螢幕try{in.close();bout.close();}catch(Exception e){}}}};@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        saveButton = (Button)this.findViewById(R.id.saveButton);        readButton = (Button)this.findViewById(R.id.readButton);        filenameEt = (EditText)this.findViewById(R.id.filename);        filecontentEt = (EditText)this.findViewById(R.id.filecontent);        saveButton.setOnClickListener(listener);        readButton.setOnClickListener(listener);    }}
四、將檔案儲存到SDCard

如果一個檔案很大,則不適用於存放在手機的儲存中;

如果手機存在sdcard,則sdcard的目錄為/mnt/sdcard目錄;

步驟1:設定模擬器支援sdcard

此時模擬器已經支援sdcard了;

步驟2:在應用中設定許可權

在AndroidManifest.xml中設定:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>    <application.../>

儲存到sdcard核心代碼:

File f = new File(Environment.getExternalStorageDirectory(),filename);out = new FileOutputStream(f,true);out.write(filecontent.getBytes("UTF-8"));

讀取sdcard核心代碼:

File f = new File(Environment.getExternalStorageDirectory(),filename);in = new FileInputStream(f);while((length=in.read(buf))!=-1){bout.write(buf,0,length);}byte[] content = bout.toByteArray();

其實主要就是儲存目錄問題;

注意:

在Android中1.5、1.6的sdcard目錄為/sdcard,而Android2.0以上都是/mnt/sdcard,因此如果我們在儲存時直接寫具體目錄會不妥,因此我們可以使用:

Environment.getExternalStorageDirectory();擷取sdcard目錄;

建議:

(1)不能純粹使用sdcard儲存法,因為如果不能判定一部手機是否存在sdcard,如果沒有,則需要提供其他解決方案,比如

儲存到手機儲存;

提示不存在sdcard;

可以使用:

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//執行儲存sdcard方法}else{//儲存到手機中,或提示}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.