我想从 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{}来实现这个独立的类文件。
你需要在你的代码中加入一些上下文来获取资源。具体来说,你需要在你的类中加入一个 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();
}