来自Res Error的Android加载文件

时间:2012-05-02 06:47:55

标签: android file file-io

我正在尝试从res / raw加载文本文件。我查看了几个代码片段并试图实现一些方法,但似乎没有一个对我有用。我目前正试图开始工作的代码就是这个

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);表示它已折旧且日食建议迁移代码。

b)getResources()无法识别,只是建议我添加一个名为getResources()的方法。

最初我想使用资源文件夹但是得到了与b)相同的错误,但是使用了getAssets()。

这是一个我正在实现的单独的类文件,名为public class PassGen{},目前有一种方法称为public String returnPass(){}

2 个答案:

答案 0 :(得分:2)

应该从Context调用函数getAssets和getResources。

如果从Activity类中调用它,它不需要前缀,但是否则你需要将上下文传递给需要这些函数的类并调用例如context.getAssets()。

答案 1 :(得分:1)

活动类:

public class ReadFileActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Read read = new Read(getApplicationContext());

    TextView helloTxt = (TextView) findViewById(R.id.hellotxt);
    helloTxt.setText(read.readTxt());
}
}

阅读课程:

public class Read {

Context ctx;

public Read(Context applicationContext) {
    // TODO Auto-generated constructor stub

    this.ctx = applicationContext;
}


public String readTxt() {

    InputStream inputStream = ctx.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();
}
}