在Android平台下,除了對應用程式的私人檔案夾中的檔案進行操作外,還可以從資源檔和 Assets 中獲得輸入資料流讀取資料,這些檔案分別放在應用程式的res/raw 目錄和 assets 目錄下,這些檔案在編譯的時候和其他檔案一起被打包。
需要注意的是,來自Resources和Assets 中的檔案只可以讀取而不能進行寫的操作,下面就通過一個例子來說明如何從 Resources 和 Assets中的檔案中讀取資訊。首先分別在res/raw 和 assets 目錄下建立兩個文字檔 "test1.txt" 和 "test2.txt" 用以讀取,結構如。
為了避免字串轉碼帶來的麻煩,可以將兩個文字檔的編碼格式設定為UTF-8。設定編碼格式的方法有很多種,比較簡單的一種是用 Windows 的記事本開啟文字檔,在另存新檔對話方塊中編碼格式選擇"UTF-8" ,如。
看一下運行後的效果。
下面我們就來看看代碼吧。
Activity02
Java代碼 {
function onclick()
{
dp.sh.Toolbar.CopyToClipboard(this);return false;
}
}" href="http://byandby.javaeye.com/blog/835744">
- package xiaohang.zhimeng;
-
- import java.io.InputStream;
- import org.apache.http.util.EncodingUtils;
- import android.app.Activity;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.widget.TextView;
-
- public class Activity02 extends Activity{
-
- public static final String ENCODING = "UTF-8";
- TextView tv1;
- TextView tv2;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- tv1 = (TextView)findViewById(R.id.tv1);
- tv1.setTextColor(Color.RED);
- tv1.setTextSize(15.0f);
- tv2 = (TextView)findViewById(R.id.tv2);
- tv2.setTextColor(Color.RED);
- tv2.setTextSize(15.0f);
- tv1.setText(getFromRaw());
- tv2.setText(getFromAssets("test2.txt"));
- }
-
- //從resources中的raw 檔案夾中擷取檔案並讀取資料
- public String getFromRaw(){
- String result = "";
- try {
- InputStream in = getResources().openRawResource(R.raw.test1);
- //擷取檔案的位元組數
- 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;
- }
-
- //從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;
- }
- }
轉http://byandby.javaeye.com/blog/835744