通常,如果Android开发者有些文件比如音频,视频,.html,.mp3等等这些文件不希望编译器编译而保持原始原貌打包进apk文件(这在游戏开发中很常见和普遍,如游戏用到的游戏音乐、图等资源),那么可以使用Android在res目录下的res/raw保存。res/raws目录下的文件将不被Android编译成二进制,Android将这些文件资源保持原状原封不动的打包进最终编译发布时候的apk文件。
怎样读取raw文件:
package com.zzw.testraw; import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream; import android.app.Activity;
import android.os.Bundle;
import android.util.Log; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main); readRaw();
} private void readRaw() {
InputStream is = getResources().openRawResource(R.raw.hello); try {
byte[] data = readByteDataFromInputStream(is);
String content = new String(data, 0, data.length, "UTF-8");
Log.d(TAG, content);
} catch (IOException e) {
e.printStackTrace();
} } private byte[] readByteDataFromInputStream(InputStream is) throws IOException {
BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final int BUFFER_SIZE = 2 * 1024; int c = 0;
byte[] buffer = new byte[BUFFER_SIZE]; // 写成baos.write(buffer, 0, c)的原因是读多少写多少
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
} byte[] data = baos.toByteArray();
baos.flush(); baos.close();
is.close(); return data; }
}