Android中的檔案讀寫全面總結

來源:互聯網
上載者:User

標籤:android   檔案讀寫   

轉載請註明出處:http://blog.csdn.net/bettarwang/article/details/41625187

在深入分析Java中的I/O類的特徵及適用場合 一文中,我詳細介紹了Java中的I/O,但是,如果以為Android中的I/O與Java中一樣,那就大錯特錯了。實際上,它們有一定的相同之外,但更多的是區別,因為Android系統中的檔案存放位置不同,讀取方式也不一樣。下面將詳細介紹Android中的檔案讀寫:

一、資源檔的讀取,不需要在Manifest檔案中添加許可權

1.從resource中的asset中讀取檔案,要注意的是asset中的檔案只能讀而不能寫

         

public static void readFromAsset(Context context,String fileName){try{    InputStream in=context.getResources().getAssets().open(fileName);    int length=in.available();    byte[]buffer=new byte[length];        in.read(buffer);    in.close();    String content=new String(buffer,"UTF-8");    ToastUtils.showShortToast(context, content);    }    catch(IOException e)    {    e.printStackTrace();    }}
2.從resource的raw中讀取檔案,與上面的一樣,也是只能讀取而不能寫入

public static void readFromRaw(Context context,int rawResId){      InputStream in=context.getResources().openRawResource(rawResId);      try      {      int length=in.available();      byte[]buffer=new byte[length];      in.read(buffer);            String res=EncodingUtils.getString(buffer, "UTF-8");            }     catch(IOException ex)     {     ex.printStackTrace();     }     finally     {     if(in!=null)     {     try     {     in.close();     }     catch(Exception e)     {     e.printStackTrace();     }     }     }}
      看到上面兩段範例程式碼可能有人會問,會什麼不想Java中那樣使用try(InputStream in=context.getResources().getAssets().open(fileName))這種autoclose的方式,但是實際上它需要Java SE1.7的版本才支援,而目前的Android版本並不支援,因而無法使用這種方法。

二、讀寫應用程式套件名目錄(即/data/data/packagename)下的檔案

首先是讀檔案

public static void readFromPackage(Context context,String fileName){try{FileInputStream fis=context.openFileInput(fileName);int length=fis.available();byte[]buffer=new byte[length];fis.read(buffer);String content=new String(buffer,"UTF-8");ToastUtils.showLongToast(context, content);}catch(IOException ex){ex.printStackTrace();}}
        然後是寫檔案,注意許可權最好是Context.MODE_PRIVATE,否則有時候會觸犯安全紅線。目前的模式主要有以下幾種:

Context.MODE_PRIVATE:為預設操作模式,代表該檔案是私人資料,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原檔案的內容,如果想把新寫入的內容追加到原檔案中,可以使用Context.MODE_APPEND;

Context.MODE_APPEND:該模式會檢查檔案是否存在,若存在就往檔案追加內容,否則就建立新檔案;

Context.MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取;

Context.WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入;

public static void writeToPackage(Context context,String fileName,String str){try{FileOutputStream fos=context.openFileOutput(fileName,Context.MODE_PRIVATE);byte[]buffer=str.getBytes();fos.write(buffer);fos.close();}catch(IOException ex){ex.printStackTrace();}}
三、讀寫sd卡中的檔案,注意要添加以下許可權:

<!--寫入資料到SD卡-->

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

<!--建立或刪除SD卡中的檔案-->

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

首先是從SD卡讀取檔案

     public void readFromSdcard(Context context,String fileName)     {     try     {     FileInputStream fis=new FileInputStream(fileName);     int length=fis.available();     byte[]buffer=new byte[length];     fis.read(buffer);          String content=new String(buffer,"UTF-8");     ToastUtils.showLongToast(context, content);      }     catch(IOException ex)     {     ex.printStackTrace();     }     }
然後是寫入檔案到SD卡:

  public static void writeToSdCardFile(byte[]buffer,Context context,String fileName)     {     try     {     FileOutputStream fos=new FileOutputStream(fileName);     fos.write(buffer);     fos.close();     }     catch(IOException ex)     {     ex.printStackTrace();     }          }
當然,上面只是進行了最基礎的樣本,至於擷取到檔案流之後的封裝問題(如採用緩衝流等),就深入分析Java中的I/O類的特徵及適用場合 一文中介紹得完全一樣了,也建議在實際使用時不要採用最基本的檔案操作流,由於在之前的文章中詳細講過,這裡就不展開討論了。


Android中的檔案讀寫全面總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.