读取资源文件
资源文件一般放到assets目录下,读取方法如下:
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetsManager.open("dir/filename.text");
示例代码如下:package com.example.assetstest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.view.Menu;
import android.widget.TextView;
public class AssetsTest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assets_test);
TextView textView = (TextView)findViewById(R.id.textView);
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("text/text.txt");
String text = loadTextFile(inputStream);
textView.setText(text);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String loadTextFile(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int len = 0;
while ((len = inputStream.read(bytes)) > 0) {
byteArrayOutputStream.write(bytes, 0, len);
}
return new String(byteArrayOutputStream.toByteArray(), "UTF8");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.assets_test, menu);
return true;
}
}