做Android開發近半年了,東西越學越多,硬盤容量越來越小。很多東西找起來也不方便,為此,我打算從今天起把工作中學到的東西整理起來,寫成日記。也希望與廣大網友分享我的經驗。一同進步。今天主要介紹文件讀取。下面講講原理。如果大家不感興趣,可以直接跳過。
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。
需要注意的是,來自Resources和Assets 中的文件只可以讀取而不能進行寫的操作
以下為從Raw文件中讀取:
代碼
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();
}
}
以下為直接從assets讀取
代碼
public String getFromAssets(String fileName){
try {
InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
BufferedReader bufReader = new BufferedReader(inputReader);
String line="";
String Result="";
while((line = bufReader.readLine()) != null)
Result += line;
return Result;
} catch (Exception e) {
e.printStackTrace();
}
}
當然如果你要得到內存流的話也可以直接返回內存流!
接下來,我們新建一個工程文件,命名為AssetsDemo。
然后建立一個布局文件,如下,很簡單,無需我多介紹,大家一看就明白。
:
然后呢,我從網上找了段文字,存放在assets文件目錄下,取名為health.txt 這就是今天我們要讀取的文件啦。這個.txt文件,我們可以直接雙擊查看。如下所示。
接下來,就是今天的重頭戲,Android讀取文件的核心代碼。就直接貼代碼了。
package com.assets.cn;
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 AssetsDemoActivity extends Activity {
public static final String ENCODING = "UTF-8";
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView)findViewById(R.id.tv1);
tv1.setTextColor(Color.BLACK);
tv1.setTextSize(25.0f);
tv1.setText(getFromAssets("health.txt"));
}
//從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;
}
}
這里是mainfest文件。
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AssetsDemoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
最后,我們運行一下程序。
細心的朋友也行會發現,這其實就是一個簡單的閱讀器了,哈哈......
ok,全部講解完畢,大家有不明白的可以給我留言。
====》源碼下載:http://download.csdn.net/detail/gsg8709/4118291