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();
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧