android 文件讀取(assets、raw)


      

  

    需要注意的是,來自Resources和Assets 中的文件只可以讀取而不能進行寫的操作。

    assets文件夾里面的文件都是保持原始的文件格式,需要用AssetManager以字節流的形式讀取文件。
      1. 先在Activity里面調用getAssets() 來獲取AssetManager引用。
      2. 再用AssetManager的open(String fileName, int accessMode) 方法則指定讀取的文件以及訪問模式就能得到輸入流InputStream。 
      3. 然后就是用已經open file 的inputStream讀取文件,讀取完成后記得inputStream.close() 。
      4.調用AssetManager.close() 關閉AssetManager。
 
 
 
從assets 文件夾中獲取文件並讀取數據
//從assets 文件夾中獲取文件並讀取數據
public String getFromAssets(String fileName){
   String result = "";
   try {
InputStream in = getResources().getAssets().open(fileName);
//獲取文件的字節數
int lenght = in.available();
//創建byte數組
byte[]  buffer = new byte[lenght];
//將文件中的數據讀到byte數組中
in.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

 

 

public String getFromRaw(){ 
            try { 
                InputStreamReader inputReader = new InputStreamReader( getResources().openRawResource(R.raw.test1));
                BufferedReader bufReader = new BufferedReader(inputReader);
                String line="";
                String Result="";
                while((line = bufReader.readLine()) != null)
                    Result += line;
                return Result;
            } catch (Exception e) { 
                e.printStackTrace(); 
            }             
    } 

 

轉  http://www.cnblogs.com/greatverve/archive/2012/03/08/android-assets.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM