Android 檔案的讀取與寫入

來源:互聯網
上載者:User

一:Android中檔案讀取更具檔案位置可分為三種:

第一種:從asset讀取資料:

 //方法:從asset中擷取檔案並讀取資料    public String getFromAsset(String fileName){    String result="";    try{    InputStream in = getResources().getAssets().open(fileName);//從Assets中的檔案擷取輸入資料流    int length = in.available();//擷取檔案的位元組數        byte [] buffer = new byte[length];//建立byte數組        in.read(buffer);//將檔案中的資料讀取到byte數組中        result = EncodingUtils.getString(buffer, ENCODING);//將byte數群組轉換成指定格式的字串    }    catch(IOException e){    e.printStackTrace();//捕獲異常並列印    }    catch(Exception e){    e.printStackTrace();    }    return result;    }

第二種:從resource中的raw檔案夾中讀取資料:

//方法:從resource中的raw檔案夾中擷取檔案並讀取資料    public String getFromRaw(String fileName){    String result = "";        try{        InputStream in = getResources().openRawResource(R.raw.test1);//從Resources中raw中的檔案擷取輸入資料流        int length = in.available();//擷取檔案的位元組數        byte [] buffer = new byte[length];//建立byte數組        in.read(buffer);//將檔案中的資料讀取到byte數組中        result = EncodingUtils.getString(buffer, ENCODING);//將byte數群組轉換成指定格式的字串           in.close();//關閉輸入資料流        }        catch(IOException e){    e.printStackTrace();//捕獲異常並列印    }    catch(Exception e){    e.printStackTrace();    }    return result;    }

第三種:從系統檔案或sd卡讀取資料:

//方法:開啟指定檔案,讀取其資料,返回字串對象   public String readFileData(String fileName){   String result="";   try{   FileInputStream fin = openFileInput(fileName);//獲得FileInputStream對象   int length = fin.available();//擷取檔案長度   byte [] buffer = new byte[length];//建立byte數組用於讀入資料   fin.read(buffer);//將檔案內容讀入到byte數組中       result = EncodingUtils.getString(buffer, ENCODING);//將byte數群組轉換成指定格式的字串   fin.close();//關閉檔案輸入資料流   }   catch(Exception e){   e.printStackTrace();//捕獲異常並列印   }   return result;//返回讀到的資料字串   }    }

二:相對於讀取資料寫入檔案就少了檔案寫入只能寫入系統檔案,sd卡檔案上

兩者方法通用:

void writeData(String filename,String msg){    try {FileOutputStream fos=this.openFileOutput(filename, MODE_PRIVATE);byte[] buf=msg.getBytes();fos.write(buf);fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}    }

ok,就這些了!

聯繫我們

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