在我的程序中,当玩家提交分数时,它会被添加到名为 localHighScores
的本地文本文件中。这是玩家在该特定设备上取得的前五名得分列表。
我不确定如何使用 FileOutputStream
写入新行(如果您知道请分享),所以我在每个乐谱之间输入了一个空格。因此,我要做的是当玩家点击提交
时,程序将打开文件并读取保存的任何当前数据。它会将它保存到一个 String Array
中,每个元素都是文本文件中五个分数之一,当它在文件中遇到一个“空格”时,它会将刚刚读取的分数添加到写入数组中元素
我目前的代码如下:
String space = " ";
String currentScoreSaved;
String[] score = new String[5];
int i = 0;
try
{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("localHighScore.txt")));
String inputString;StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null && i < 6)
{
if((inputString = inputReader.readLine()) != space)
{
stringBuffer.append(inputString + "\n");
i++;
score[i] = stringBuffer.toString();
}
}
currentScoreSaved = stringBuffer.toString();
FileOutputStream fos = openFileOutput("localHighScore.txt", Context.MODE_PRIVATE);
while (i < 6)
{
i++;
fos.write(score[i].getBytes());
fos.write(space.getBytes());
}
fos.write(localHighScore.getBytes());
//fos.newLine(); //I thought this was how you did a new line but sadly I was mistaken
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
现在您会注意到,如果达到新的高分,这不会重新安排分数。我打算下一步做。目前,我只是想让程序执行在当前数据中读取的主要内容,将其粘贴到数组中,然后将其与新分数一起打印回该文件
任何想法这可能是如何工作的,因为即使我事先在文本文件中得分,目前它也没有打印出任何东西
最佳答案
我只是 Java 编程的一年级学生,我是 stackoverflow.com 的新用户,所以请原谅我,如果 android 编码有一些我不知道的特殊规则,这会阻止这种简单而谦虚的工作的例子。但这里是我将如何以最简单的方式读取文件。
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
Scanner readFile = new Scanner( tempFile );
// Assuming that you can structure the file as you please with fx each bit of info
// on a new line.
int counter = 0;
while ( readFile.hasNextLine() ) {
score[counter] = readFile.nextLine();
counter++;
}
至于写回文件?将它放在一个完全不同的方法中,并简单地制作一个类似 toString 的简化方法,以您希望的方式在文件中打印出所有值,然后创建一个类似“loadToFile”的方法并使用 to string 方法打印回来使用打印流进入文件,如下所示。
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
PrintStream write = new PrintStream(tempFile);
// specify code for your particular program so that the toString method gets the
// info from the string array or something like that.
write.print( <objectName/this>.toStringLikeMethod() );
// remember the /n /n in the toStringLikeMethod so it prints properly in the file.
同样,如果这是您已经知道的事情,但在这种情况下这是不可能的,请忽略我,但如果不是,我希望它有用。至于异常(exception)情况,你自己猜吧。 ;)
关于java - 读取文本文件中的五个分数,然后将它们打印回来,并将新分数添加到列表中 - ANDROID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14718125/