使用ADB时,Android Studio“找不到文件”,桌面版本有效

时间:2018-08-10 15:18:28

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

每当我尝试通过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)

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

好吧,当使用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

答案 1 :(得分:0)

找到答案: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();

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