Android:读取assets资源

读取assets资源

  • 博客分类: 
  • java
Java代码   收藏代码
  1. import java.io.ByteArrayOutputStream;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.res.AssetManager;  
  7. import android.os.Bundle;  
  8. import android.util.Log;  
  9. import android.widget.EditText;  
  10.   
  11. /** 
  12.  * Class which shows how to use assets 
  13.  * 
  14.  * @author FaYnaSoft Labs 
  15.  */  
  16. public class Main extends Activity {  
  17.     private EditText firstField;  
  18.     private EditText secondField;  
  19.   
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.         AssetManager assetManager = getAssets();  
  25.         String[] files = null;  
  26.         try {  
  27.             files = assetManager.list("image");  
  28.         } catch (IOException e) {  
  29.             Log.e("tag", e.getMessage());  
  30.         }  
  31.         firstField = (EditText) findViewById(R.id.firstId);  
  32.         firstField.setText(Integer.toString(files.length) + " file. File name is "  
  33.                 + files[0]);  
  34.         InputStream inputStream = null;  
  35.         try {  
  36.             inputStream = assetManager.open("readme.txt");  
  37.         } catch (IOException e) {  
  38.             Log.e("tag", e.getMessage());  
  39.         }  
  40.   
  41.         String s = readTextFile(inputStream);  
  42.         secondField = (EditText) findViewById(R.id.secondId);  
  43.         secondField.setText(s);  
  44.     }  
  45.   
  46.     /** 
  47.      * This method reads simple text file 
  48.      * @param inputStream 
  49.      * @return data from file 
  50.      */  
  51.     private String readTextFile(InputStream inputStream) {  
  52.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
  53.         byte buf[] = new byte[1024];  
  54.         int len;  
  55.         try {  
  56.             while ((len = inputStream.read(buf)) != -1) {  
  57.                 outputStream.write(buf, 0, len);  
  58.             }  
  59.             outputStream.close();  
  60.             inputStream.close();  
  61.         } catch (IOException e) {  
  62.         }  
  63.         return outputStream.toString();  
  64.     }  
  65. }  

 AssetManager assetManager = getAssets();

/assets 文件夹/image 包含icon.png . 还有一个文本readme.txt包含Hello, World!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值