【问题标题】:Android Reading and writing a file to and from an arrayAndroid 从数组中读取和写入文件
【发布时间】:2014-08-19 19:24:34
【问题描述】:

首先我要说的是,我已经在 StackOverflow 和其他地方研究了各种解决方案,但都没有解决我的问题。我承认我在这方面的知识有些欠缺,很抱歉我很菜鸟。

我想做一件我认为很简单的事情。如果文件尚不存在,我的应用会在启动时创建一个文件,并用 30 个“0.0”填充它,每个文件位于不同的行(这已成功完成)。

然后,当您通过一个级别时,目的是读取文件,0.0 并将每个元素分配给数组的一个元素,将剩余时间(例如,2.5)分配给适当的位置([ 0] 用于第一级,[1] 用于第二级等),并将其写回文件以跟踪玩家通过每个级别时剩余的时间。

问题变成了,尽管它确实将适当位置的分数写回文件中(我正在测试级别 1,所以在位置 [0]),所有其他 0.0 都变为“null”。所以我知道某个地方有一个我一定看不到的错误,经过几天尝试各种解决方案的几个小时后,我终于决定在这里寻求帮助。这是下面的代码:

try {
        String[] scoreArray = new String[30];
    File sdCard = Environment.getExternalStorageDirectory();
    File myFile = new File(sdCard.getAbsolutePath());
   // myFile.createNewFile();
    File file = new File(myFile, "RLGLscores.txt");
    FileOutputStream fOut = new FileOutputStream(file);
    String newLine = System.getProperty("line.separator");
    OutputStreamWriter myOutWriter = 
                            new OutputStreamWriter(fOut);
    FileInputStream fis = new FileInputStream(file);
    BufferedReader myReader = new BufferedReader(
            new InputStreamReader(fis));
    String data = "";
    int i = 0;
    while ((data = myReader.readLine()) != null) {
            scoreArray[i] = data;
        i++;

    }
    myReader.close();
    scoreArray[0] = timerStringFormat;

    for (int j = 0; j < 30; j++) {
    myOutWriter.write(scoreArray[j] + newLine);
    }

    myOutWriter.close();
    fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

timerStringFormat 是以字符串形式保存剩余时间的字符串。再说一次,我对此很陌生。我的游戏快完成了,我很惊讶我能做到这一点。但任何帮助将不胜感激。

【问题讨论】:

    标签: android arrays file io


    【解决方案1】:

    打开文件进行写入会将其截断为零长度。如果您稍后尝试从中读取,您只会看到一个空文件。

    要解决这个问题,首先读取内容,关闭阅读器,然后打开输出流并将修改后的内容写回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多