我正在尝试读取文本文件但在openRawResource中获取异常,我的文本文件位于drawable文件夹中,这是我的代码。
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = getApplicationContext().getResources().openRawResource(R.drawable.dict_7letter);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
Log.d("from dict", "........."+buf);
}
答案 0 :(得分:0)
将您的文本文件放在资源中并编写以下代码以读取文本文件:
public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
答案 1 :(得分:0)
您可以将文本文件放在资源下的原始文件夹中。 然后以
的形式访问它getResources().openRawResource(R.raw.dict_7letter);
如果您需要将其保存在可绘制文件夹中,请使用
访问它getResources().getIdentifier("drawable/dict_7letter","drawable", getPackageName())
InputStream ins = getResources().openRawResource(getResources().getIdentifier("drawable/dict_7letter","drawable", getPackageName()));