markdowneide 2013-08-26 10:03 采纳率: 0%
浏览 867

从Res中加载文件时的错误

我想从 res/raw中加载一个text文件。我已经看了一些代码片段但是没有找到能实现的方法。

TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
        helloTxt.setText(readTxt());
    }
     private String readTxt() {
     InputStream inputStream = getResources().openRawResource(R.raw.hello);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     int i;
     try {
         i = inputStream.read();
         while (i != -1) {
             byteArrayOutputStream.write(i);
             i = inputStream.read();
         }
         inputStream.close();
     }
     catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
     return byteArrayOutputStream.toString();

a)(TextView)findViewById(R.id.hellotxt);这行提示,Eclipses推荐移除代码。
b)getResources()这行提醒我添加 getResources()方法。
这是一个独立的类文件,我在 public String returnPass(){}方法调用 public class PassGen{}来实现这个独立的类文件。

  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-01-13 20:00
    关注

    你需要在你的代码中加入一些上下文来获取资源。具体来说,你需要在你的类中加入一个 Context 变量,并在构造函数中传入这个变量。然后你就可以使用这个变量来调用 getResources() 了。


    例如:

    public class PassGen {
        private Context mContext;
    
        public PassGen(Context context) {
            mContext = context;
        }
    
        public String readTxt() {
            InputStream inputStream = mContext.getResources().openRawResource(R.raw.hello);
            // rest of the code
        }
    }
    

    然后,在调用 PassGen 类的时候,将当前的上下文传入构造函数中即可。
    例如:

    PassGen passgen = new PassGen(getApplicationContext());
    

    另外,从上面代码片段中,我们看到你在使用 InputStream 读取文件内容时,你是通过读取每一个字节来实现的。这种方法会有效率问题。更好的方法是使用 InputStreamReader 和 BufferedReader 类来读取文件,如下所示:

    public String readTxt() {
            InputStream inputStream = mContext.getResources().openRawResource(R.raw.hello);
            InputStreamReader inputreader = new InputStreamReader(inputStream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line;
            StringBuilder text = new StringBuilder();
    
            try {
                while (( line = buffreader.readLine()) != null) {
                    text.append(line);
                    text.append('\n');
                }
            } catch (IOException e) {
                return null;
            }
            return text.toString();
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功