【问题标题】:Android studio "File not found" when using ADB, Desktop version works使用 ADB 时 Android Studio “找不到文件”,桌面版有效
【发布时间】:2019-01-18 06:01:31
【问题描述】:

每当我尝试通过 ADB 在手机上运行我的 libdgx 应用程序时,android studio 都无法在“android/assets”文件夹中找到文件。但是,当我运行桌面版本时,它运行良好。

我正在使用它来读取文件:

File file = new File("BlocksProgression.txt");
reader = new BufferedReader(new FileReader(file));

如上所述,当我运行桌面启动器时,这工作正常,但 android 启动器返回此错误:

W/System.err: java.io.FileNotFoundException: BlocksProgression.txt (No such file or directory)

我已经搜索了一个多小时,但似乎找不到正确设置资产文件夹的方法。

任何帮助将不胜感激。

【问题讨论】:

  • 交叉检查你的文件名,Android file-system is case sensitive.

标签: java android android-studio libgdx file-not-found


【解决方案1】:

找到答案:https://github.com/libgdx/libgdx/wiki/File-handling#reading-from-a-file

原来 Libgdx 希望您使用 FileHandle 对象来读取文件。使用这个我的代码变成:

FileHandle file = Gdx.files.internal("BlocksProgression.txt");
String data = file.readString();

这只是将文本作为字符串返回。希望这可以帮助一些人。

【讨论】:

    【解决方案2】:

    好吧,当使用File file = new File("BlocksProgression.txt") 时,您不是从资产中读取,而是从默认文件目录中读取,从资产中读取文件的正确方法如下

    BufferedReader reader = null;
    try {
        reader = new BufferedReader(
            new InputStreamReader(getAssets().open("BlocksProgression.txt"), "UTF-8")); 
    
        // do reading, usually loop until end of file reading 
        String mLine;
        while ((mLine = reader.readLine()) != null) {
           //process line
           ...
        }
    } catch (IOException e) {
        //log the exception
    } finally {
        if (reader != null) {
             try {
                 reader.close();
             } catch (IOException e) {
                 //log the exception
             }
        }
    }
    

    此代码来自answer

    【讨论】:

    • 感谢您的回答,我知道我没有像这样从资产文件夹中读取。当我尝试调用 getAssets 时,它无法解析该方法,因为它不在那个类中,但是,我不知道它在哪个类中,我是否必须扩展一些类以便我可以调用 getAssets。哪个类包含 getAssets 函数?谢谢
    • 编辑:所以我发现 getAssets 只能在活动中调用,否则我应该使用静态类 ContextInstance,但是,我似乎找不到要导入的类。另外我无法扩展“活动”(也没有找到),也许我的项目设置不正确。
    • 也许试试这个导入,import android.app.Activity;
    • 嗯,这不起作用,但我找到了问题所在。我会将其发布为其他有相同问题的人的答案。无论如何感谢您的帮助!
    猜你喜欢
    • 2020-10-21
    • 2020-11-24
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多