zoukankan      html  css  js  c++  java
  • Android开发之assets文件夹中资源的获取

    assets中的文件都是保持原始的文件格式,需要使用AssetManager以字节流的形式读取出来

    步骤:

    • 1. 先在Activity里面调用getAssets() 来获取AssetManager引用。
    • 2. 再用AssetManager的open(String fileName, int accessMode) 方法则指定读取的文件以及访问模式就能得到输入流InputStream。
    • 3. 然后就是用已经open file 的inputStream读取文件,读取完成后记得inputStream.close() 。
    • 4.调用AssetManager.close() 关闭AssetManager。

    需要注意的是,来自assets 中的文件只可以读取而不能进行写的操作

    代码:

     1  private void copyDataBase(String baseName) {
     2         OutputStream outputStream = null;
     3         InputStream inputStream = null;
     4         File file = new File(getFilesDir(), baseName);
     5         if ( file.exists() ) {
     6             return;
     7         }
     8         try {
     9             outputStream = new FileOutputStream(file);
    10             inputStream = getAssets().open(baseName);
    11             int len;
    12             byte[] buffer = new byte[1024];
    13             while ( (len = inputStream.read(buffer)) != -1 ) {
    14                 outputStream.write(buffer, 0, len);
    15             }
    16         } catch ( IOException e ) {
    17             e.printStackTrace();
    18         } finally {
    19             try {
    20                 inputStream.close();
    21                 outputStream.close();
    22             } catch ( Exception e ) {
    23                 e.printStackTrace();
    24             }
    25 
    26         }
    27     }
  • 相关阅读:
    eclipse如何卸载adt插件
    Android中的Toast.LENGTH_SHORT
    Frogger
    - Oil Deposits 深搜,就是所谓的dfs
    Aggressive cows
    Phone List
    Word Amalgamation
    Street Numbers
    Charm Bracelet——背包问题
    函数参考
  • 原文地址:https://www.cnblogs.com/liyiran/p/5315331.html
Copyright © 2011-2022 走看看