Android 访问assets下的文件

assets下经常可以放一些比较大的资源,对于这些资源我们如何访问。

步骤

1.获取AssetManager。

AssetManager am = getResources().getAssets();

2.利用AssetManager的open(String filePath)方法打开对应的输入流。

InputStream is = am.open(assetsFileName);

读取图片文件保存到SD卡示例代码

public  boolean saveToSDCard(String localFilePath, String fileName,
            Bitmap bitmap) {
        String extraPath = Environment.getExternalStorageDirectory().toString();
        // 使用绝对路径
        extraPath = extraPath + "/" + "PaperCut"+"/"+localFilePath;
        // String path = null;
        File file = new File(extraPath);
        if (!file.exists())
            file.mkdirs();
        try {
            filePath = file.getPath() + "/" + fileName + ".png";
            File newFile = new File(filePath);
            if (newFile.exists()) {
                Toast.makeText(getApplicationContext(), R.string.finishTips1, // 已经保存过啦亲
                        Toast.LENGTH_SHORT).show();
                return true;
            }else {
                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                // 另一种格式的结尾
                // bitmap.compress(CompressFormat.PNG, 50, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            // System.out.println(e.toString());
            return false;
        }
        return true;
    }
    private Bitmap getImageFromAssetsFile(int  position)
      {
          //Bitmap image = null;
          Bitmap image = null;
          String assetsFileName = null;
          assetsFileName = "album/"+is.imageMyChooseName.get(position)+"/1.png";
          //AssetManager从assets文件夹中获取资源
          AssetManager am = getResources().getAssets();
          try
          {
              InputStream is = am.open(assetsFileName);
              //从InputStream解码生成image
              image = BitmapFactory.decodeStream(is);
              is.close();
          }
          catch (IOException e)
          {
              e.printStackTrace();
          }
          return image;
      }
      //调用
          saveToSDCard("album","filePath"),getImageFromAssetsFile(position));
上一篇:Redis入门之增删改查等常用命令总结


下一篇:使用控制台对Redis执行增删改查命令