通常,如果Android开发者有些文件比如音频,视频,.html,.mp3等等这些文件不希望编译器编译而保持原始原貌打包进apk文件(这在游戏开发中很常见和普遍,如游戏用到的游戏音乐、图等资源),那么可以使用Android在res目录下的res/raw保存。res/raws目录下的文件将不被Android编译成二进制,Android将这些文件资源保持原状原封不动的打包进最终编译发布时候的apk文件。
怎样读取raw文件:
1 package com.zzw.testraw; 2 3 import java.io.BufferedInputStream; 4 import java.io.ByteArrayOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 8 import android.app.Activity; 9 import android.os.Bundle; 10 import android.util.Log; 11 12 public class MainActivity extends Activity { 13 14 private static final String TAG = "MainActivity"; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 // setContentView(R.layout.activity_main); 20 21 readRaw(); 22 } 23 24 private void readRaw() { 25 InputStream is = getResources().openRawResource(R.raw.hello); 26 27 try { 28 byte[] data = readByteDataFromInputStream(is); 29 String content = new String(data, 0, data.length, "UTF-8"); 30 Log.d(TAG, content); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } 34 35 } 36 37 private byte[] readByteDataFromInputStream(InputStream is) throws IOException { 38 BufferedInputStream bis = new BufferedInputStream(is); 39 40 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 41 42 final int BUFFER_SIZE = 2 * 1024; 43 44 int c = 0; 45 byte[] buffer = new byte[BUFFER_SIZE]; 46 47 // 写成baos.write(buffer, 0, c)的原因是写多少读多少 48 while ((c = bis.read(buffer)) != -1) { 49 baos.write(buffer, 0, c); 50 baos.flush(); 51 } 52 53 byte[] data = baos.toByteArray(); 54 baos.flush(); 55 56 baos.close(); 57 is.close(); 58 59 return data; 60 61 } 62 }
时间: 2024-10-11 16:01:47