閱讀732 返回首頁    go 阿裏雲 go 技術社區[雲棲]


AssetManager asset的使用

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:andro 

    android:orientation="vertical" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    >
 
<TextView 
 
    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/hello" 

    />
 
    <EditText android: 

     android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/hello" 

    />
 
    <EditText android: 

     android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/hello" 

    />
 
 
 
</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;
 
importandroid.app.Activity ;
 
import android.content.res.AssetManager;
 
importandroid.os.Bundle ;
 
import android.util.Log;
 
import android.widget.EditText;
  
 
publicclass GetAssets extends Activity {
 
 private EditText firstField;
 
 private EditText secondField;
 
 @Override
 
 publicvoid 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 ;
 
  try {
 
   inputStream = assetManager.open("readme.txt");
 
  } catch (IOException e) {
 
   Log.e ("tag", e.getMessage());
 
  }
 
  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;
 
  try {
 
   while ((len = inputStream.read(buf)) != -1) {
 
    outputStream.write(buf, 0, len);
 
   }
 
   outputStream.close();
 
   inputStream.close();
 
  } catch (IOException e) {
 
  }
 
  return outputStream.toString();
 
 }
 
}


最後更新:2017-04-02 17:51:24

  上一篇:go C# URL帶中文參數的解決辦法
  下一篇:go jsp中實現倒計時簡單代碼