java - 在 Android 中访问资源文件

标签 java android file resources

我的/res/raw/文件夹 (/res/raw/textfile.txt) 中有一个资源文件,我正在尝试从我的 android 应用程序中读取该文件以进行处理。

public static void main(String[] args) {

    File file = new File("res/raw/textfile.txt");
    
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    try {
      fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      while (dis.available() != 0) {
              // Do something with file
          Log.d("GAME", dis.readLine()); 
      }

      fis.close();
      bis.close();
      dis.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

我尝试了不同的路径语法,但总是得到 java.io.FileNotFoundException 错误。如何访问/res/raw/textfile.txt 进行处理? File file = new File("res/raw/textfile.txt");是Android中的错误方法吗?


***** 答案:*****

// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
       
public void LoadText(int resourceId) {
    // The InputStream opens the resourceId and sends it to the buffer
    InputStream is = this.getResources().openRawResource(resourceId);
    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();
    }
}

请注意,这不会返回任何内容,但会将内容逐行打印为日志中的 DEBUG 字符串。

最佳答案

如果您的 Activity/Widget 调用中的 res/raw/textfile.txt 中有一个文件:

getResources().openRawResource(...) 返回一个 InputStream

点实际上应该是在 R.raw 中找到的整数...对应于您的文件名,可能是 R.raw.textfile(通常是不带扩展名的文件名)

new BufferedInputStream(getResources().openRawResource(...)); 然后将文件内容作为流读取

关于java - 在 Android 中访问资源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4081763/

相关文章:

java - 为什么 Tomcat 服务器没有最新的 HTML 更新?

java - 如何获取 Android 中的所有联系人并忽略仅电子邮件联系人

java - 获取上传进度

gridView 中的 Android 图像顺序错误

java - 摩尔斯电码翻译

android - 代号一HTML解析

c - 如何不阻止设备被弹出/安全移除?

c++ - 逐行从文本文件中读取数据,在 C++ 中用多个定界符分隔

python - 在每行的开头插入字符串

java - 如何在 ListView android 上方添加固定按钮?