Android-读取assets和raw资源文件

本文介绍了一个名为ResourceUtils的工具类,该类提供了从Android项目的raw和assets文件夹中加载文本和图片资源的方法。通过使用此类,开发者可以轻松地读取资源文件内容或将图片资源转换为Bitmap对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.EncodingUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ResourceUtils {
 
   publicstatic final String ENCODING = "UTF-8";

    
    //从resources中的raw 文件夹中获取文件并读取数据
    publicstatic String getFromRaw(Context context, int rawResourceId){
      String result = "";
      try {
         InputStream in =context.getResources().openRawResource(
               rawResourceId);
         // 获取文件的字节数
         int lenght = in.available();
         // 创建byte数组
         byte[] buffer = new byte[lenght];
         // 将文件中的数据读到byte数组中
         in.read(buffer);
         result = EncodingUtils.getString(buffer,ENCODING);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
    }

    // 从assets文件夹中获取文件并读取数据
    publicstatic String getFromAssets(Context context, String fileName){
      String result = "";
      try {
         InputStream in =context.getResources().getAssets().open(fileName);
         // 获取文件的字节数
         int lenght = in.available();
         // 创建byte数组
         byte[] buffer = new byte[lenght];
         // 将文件中的数据读到byte数组中
         in.read(buffer);
         result = EncodingUtils.getString(buffer,ENCODING);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
    }

    publicstatic Bitmap getImageFromAssets(Context context, String fileName){
      Bitmap bitmap;
      try {
         InputStream is =context.getResources().getAssets().open(fileName);
         bitmap = BitmapFactory.decodeStream(newFlushedInputStream(is));
         return bitmap;
      } catch (Exception e) {
         e.printStackTrace();
      }
      return null;
    }

    static classFlushedInputStream extends FilterInputStream {
      public FlushedInputStream(InputStreaminputStream) {
         super(inputStream);
      }

      @Override
      public long skip(long n) throws IOException{
         long totalBytesSkipped = 0L;
         while (totalBytesSkipped < n){
            long bytesSkipped = in.skip(n -totalBytesSkipped);
            if (bytesSkipped == 0L) {
               int b = read();
               if (b < 0) {
                  break; // we reached EOF
               } else {
                  bytesSkipped = 1; // we read one byte
               }
            }
            totalBytesSkipped += bytesSkipped;
         }
         return totalBytesSkipped;
      }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值