【问题标题】:How to access a file from asset/raw directory如何从资产/原始目录访问文件
【发布时间】:2018-02-05 02:41:53
【问题描述】:

使用下面的代码,我试图访问存储在asset/raw 文件夹中的文件,但得到null 和

E/ERR: file:/android_asset/raw/default_book.txt (No such file or directory)

错误,我的代码是:

private void implementingDefaultBook() {
    String filePath = Uri.parse("file:///android_asset/raw/default_book.txt").toString();
    File   file     = new File(filePath);
    try {
        FileInputStream stream      = new FileInputStream(file);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("ERR ", e.getMessage());
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    }
}

【问题讨论】:

    标签: android android-assets


    【解决方案1】:

    将您的文本文件放在Android项目下的/assets目录中,并使用AssetManager类访问它。

    AssetManager am = context.getAssets();
    InputStream is = am.open("default_book.txt");
    

    或者你也可以把文件放在/res/raw目录下,从那里可以通过id访问文件,如下所示

    InputStream is = 
    context.getResources().openRawResource(R.raw.default_book);
    

    【讨论】:

    • 什么是上下文以及如何访问它
    • @PatrickYoussef 基本上 Context 是一个对象,用于执行与您的 android 应用程序相关的任何操作,例如获取资产,您需要应用程序的引用才能访问您的应用程序的资产。您可以从 Activity 之类的东西中获取此对象。阅读更多信息:stackoverflow.com/questions/3572463/what-is-context-on-android
    【解决方案2】:

    资产和资源是您的开发机器上的文件。它们不是设备上的文件。

    对于资产,请在 AssetManager 上使用 open() 以获得资产上的 InputStream。

    另外,FWIW:

    • Uri.parse("file:///android_asset/raw/default_book.txt").toString() 毫无意义,因为它为您提供了与您开始时相同的字符串

    • file:///android_asset/ 仅适用于WebView

    【讨论】:

      【解决方案3】:

      由于实际问题没有得到充分回答,我们开始吧

      InputStream is = context.getAssets().openFd("raw/"+"filename.txt")
      

      上下文可以是this 或getActivity() 或基本上任何其他上下文

      重要的是在文件名之前包含文件夹,用/分隔

      【讨论】:

        【解决方案4】:

        在 Kotlin 中我们可以实现 -

        val string = requireContext().assets.open("default_book.txt").bufferedReader().use {
                        it.readText()
                    }
        

        【讨论】:

          【解决方案5】:
          InputStream is = getAssets().open("default_book.txt");
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-09-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-11
            • 2012-09-24
            • 1970-01-01
            相关资源
            最近更新 更多