天天看點

assets 加載資源檔案

1。擷取資源的輸入流 

資源檔案 sample.txt 位于 $PROJECT_HOME/assets/ 目錄下,可以在 Activity 中通過 

Context.getAssets().open(“sample.txt”) 

方法擷取輸入流。 

注意:如果資源檔案是文本檔案則需要考慮檔案的編碼和換行符。建議使用UTF-8和Unix換行符。 

2. WebView 加載assets目錄下的html檔案 

資源檔案 sample.html 位于 $PROJECT_HOME/assets/ 目錄下,可以通過以下代碼 

WebView.loadUrl(“file:///android_asset/sample.html”); 

加載html檔案。 

Android 系統為每個新設計的程式提供了/assets目錄,這個目錄儲存的檔案可以打包在程式裡。/res 和/assets的不同點是,android不為/assets下的檔案生成ID。如果使用/assets下的檔案,需要指定檔案的路徑和檔案名。下面這個例子,顯示如何通路/assets下的内容。 

   在檔案中/assets 中建立/image子目錄,将/res/drawable下的icon.png子目錄拷貝到該目錄中。在/assets子目錄中建立readme.txt檔案,檔案中輸入文本“hello,world!!!”。 

布局檔案:main.xml 

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:orientation="vertical" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    > 

<TextView 

    android:layout_height="wrap_content" 

    android:text="@string/hello" 

    /> 

    <EditText android:id="@+id/firstId" 

     android:layout_width="fill_parent" 

    <EditText android:id="@+id/secondId" 

</LinearLayout> 

程式檔案: 

package com.cn.getassets; 

import android.app.Activity; 

import android.os.Bundle; 

import java.io.ByteArrayOutputStream; 

import java.io.IOException; 

import java.io.InputStream; 

import android.content.res.AssetManager; 

import android.util.Log; 

import android.widget.EditText; 

public class GetAssets extends Activity { 

private EditText firstField; 

private EditText secondField; 

@Override 

public void onCreate(Bundle savedInstanceState) { 

  super.onCreate(savedInstanceState); 

//  Log.d("show main.xml","ok"); 

  setContentView(R.layout.main); 

  Log.d("show main.xml","ok"); 

  AssetManager assetManager = getAssets(); 

  String[] files = null; 

  try { 

   files = assetManager.list("image"); 

  } catch (IOException e) { 

   Log.e("tag", e.getMessage()); 

  } 

  firstField = (EditText) findViewById(R.id.firstId); 

  firstField.setText(Integer.toString(files.length)+"file.File name is"+ files[0]); 

  InputStream inputStream = null; 

   inputStream = assetManager.open("readme.txt"); 

  String s = readTextFile(inputStream); 

  secondField = (EditText) findViewById(R.id.secondId); 

  secondField.setText(s); 

private String readTextFile(InputStream inputStream) { 

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 

  byte buf[] = new byte[1024]; 

  int len; 

   while ((len = inputStream.read(buf)) != -1) { 

    outputStream.write(buf, 0, len); 

   } 

   outputStream.close(); 

   inputStream.close(); 

  return outputStream.toString(); 

}

繼續閱讀