我在 android res 文件夹中的 raw 文件夹中有一个名为 words.txt 的文本文件。我不知道如何获取使用给定路径创建新文件的路径。我使用下面的代码,但似乎不起作用:
File file = new File("res/raw/words.txt").getAbsoluteFile();
String filePath = file.getAbsolutePath();
File wordFile = new File(filePath);
最佳答案
您可以按如下方式阅读raw/words.txt
:
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.words);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
注意:此代码必须在 Activity
类中,因为 this.getResources()
引用 Context.getResources()
关于Android:如何从 res 文件夹中的 R.raw 获取文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753799/