Android:如何从 res 文件夹中的 R.raw 获取文件路径?

标签 android

我在 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/

相关文章:

android - 使用android NDK编译失败

Android Gridview 和 getChildAt 与 NullPointerException

android - 在单个 ParseObject 中存储多个 ParseFile 对象

android - WebView 被切断

android - 从挂起函数异常返回对象

Android Gradient——属性的含义

android - Toast 未在 Samsung Galaxy S3 上显示(最新更新 4.1.2)

java - 如何从 MainActivity 将 url 图像添加到 Adapter ViewPager - Android

android - 如何从 EditText OnClickListener 中动态选择文本?

java - Android - 检索和使用 fragment 中的 View 位置