assets文件夾資源的訪問
需要注意的是,來自Resources和Assets 中的文件只可以讀取而不能進行寫的操作
以下爲從Raw文件中讀取:
代碼
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();
}
}
當然如果你要得到內存流的話也可以直接返回內存流!
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;
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.assets.cn"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<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>