Android ApiDemos示例解析(47):Content->Assets->Read Asset

android.Content包定义了一些类,这些类主要用于在设备上访问或是发布数据,主要有三个包构成。

  • Content 共享 (android.content) 主要用于在Application的各个部件自己共享一些数据,主要的列有Content Provider,ContentResolver用于管理和发布数据。 Intent,IntentFilter 用于Application不同组件之间发送消息。
  • Package 管理 (android.content.pm) 用于访问Android Package (.apk)定义的Activities, Permissions, Services,Signatures和Providers,主要的类为PackageManager。
  • 资源管理 (android.content.res) 用于访问应用中定义的资源,如Strings,Drawables, Media,Device Configuration等等,主要的类为Resources。

    一般来说Application把资源放在res目录下面,有些情况下Application需要使用一些自定义的文件,一种方法是将它们放在res/raw 目录下面,另外一种方法是将它们放在assets目录下,和res 目录不同的是,Android SDK不会为目录assets 下的文件生成资源ID,而是通过AssetManager 以文件的文件名来访问,放在/assets的目录机构是什么样的,使用AssetManager 访问时也是采用同样的文件结构。和res相比,assets 提供了更低一层次的资源访问。

    本例使用AssetManager来访问assets 目录下的read_asset.txt 。

    InputStream is = getAssets().open("read_asset.txt"); 
      
    // We guarantee that the available method returns the total 
    // size of the asset...  of course, this does mean that a single 
    // asset can't be more than 2 gigs. 
    int size = is.available(); 
      
    // Read the entire asset into a local byte buffer. 
    byte[] buffer = new byte[size]; 
    is.read(buffer); 
    is.close(); 
      
    // Convert the buffer into a string. 
    String text = new String(buffer); 
      
    // Finally stick the string into the text view. 
    TextView tv = (TextView)findViewById(R.id.text); 
    tv.setText(text);


     

    在Activity 中可以通过getAssets() 来取得AssetManager对象,和文件操作类似AssetManager可以通过字节流的方式来读取文件。

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值