有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java LibGDX写入文本文件并接收各种错误

我目前正在用LibGDX创建的一个游戏有一个“高分”功能,其中高分保存在一个文本文件中,然后写入或读取到屏幕上。我这里有很多错误。我尝试设置权限以允许外部文件写入,我尝试将。不同目录中的txt文件。我试过使用Gdx.files.internal() and Gdx.files.external()没有任何效果。以下是我获得和设置高分的两种方法

private int getHighScore()
{
    FileHandle scoreFile = Gdx.files.local("data/high_score.txt");
    String text = scoreFile.readString();
    int highScore = Integer.parseInt(text);
    return highScore;
}

private void setHighScore(int newScore)
{
    FileHandle scoreFile = Gdx.files.local("data/high_score.txt");
    String score = Integer.toString(newScore);
    scoreFile.writeString(score, false);
}

在游戏中死亡时(当应该显示分数时),我从LibGDX收到以下错误:

03-06 22:31:37.437: ERROR/AndroidRuntime(14533): FATAL EXCEPTION: GLThread 4617
        com.badlogic.gdx.utils.GdxRuntimeException: File not found: /data/data/hasherr.floppyfish.安卓.core/files/data/high_score.txt (Local)
        at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:133)
        at com.badlogic.gdx.backends.安卓.AndroidFileHandle.read(AndroidFileHandle.java:77)
        at com.badlogic.gdx.files.FileHandle.readString(FileHandle.java:198)
        at com.badlogic.gdx.files.FileHandle.readString(FileHandle.java:186)
        at hasherr.ghostly.main.state.DeathState.getHighScore(DeathState.java:122)
        at hasherr.ghostly.main.state.DeathState.render(DeathState.java:87)
        at hasherr.ghostly.main.state.StateManager.render(StateManager.java:37)

请注意:

File not found: /data/data/hasherr.floppyfish.安卓.core/files/data/high_score.txt (Local)

/data/data/hasherr.floppyfish.安卓.core/files/data/high_score.txt不是我游戏中的目录/文件data/high_score.txt是,这就是我试图访问的文件。我对Gdx.files.local(path)方法不是很熟悉,所以我不确定它是从哪里获得的

如何让程序使用此文本文件而不抛出错误


共 (2) 个答案

  1. # 1 楼答案

    Gdx使用您的应用程序文件夹

    从文档的“文件处理”部分:

    Files can also be stored on the internal storage, where they are readable and writable. Each installed application has a dedicated internal storage directory. This directory is again only accessible by that application. One can think of this storage as a private working area for the application.

    在图表中,您可以看到本地:

    Local files are stored relative to the application's root or working directory on desktops and relative to the internal (private) storage of the application on Android. Note that Local and internal are mostly the same on the desktop.

    如果要存储在设备内部存储器中,则应使用Gdx.files.internal("data/high_score.txt");

    参考链接:https://github.com/libgdx/libgdx/wiki/File-handling

  2. # 2 楼答案

    首先,我建议确保Highscores.txt存在于Gdx.files.local("data/high_score.txt");。为此,您可以使用:boolean exists = Gdx.files.local("Highscores.txt").exists();。如果此布尔值为false,则可以打印“无高分”,而不是读取.txt。 正如@MelihYıldız'所说的Gdx.files.local指向私有应用程序存储。但是如果您使用它来writeread数据,您就不需要关心它在哪里。只要确保您始终使用相同的FileHandle。了解所有不同的Gdx。文件夹。xxx您可以阅读this。它解释了存储数据的位置以及哪个apptype可以访问数据。 对于Highscores,您还可以考虑使用PreferencesA quick tutorial。 请注意,Preferences是存储HTML5应用程序数据的唯一可能。如果你想让你的应用成为一个网络应用,你应该灵活地考虑它们