0

我正在尝试通过使用此代码将名称和分数保存到文本文件来制作高分系统。

String text = name.getText().toString() + " " + score.getText().toString();
            appendLog(text);
        }
    });
}

public void appendLog(String text)
{       
   File logFile = new File("sdcard/logger.file");
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }

我有没有办法对每行中存在的分数进行排序并输出名称及其相应的分数?谁能帮我怎么做?谢谢你。

4

2 回答 2

2

让一行代表您的数据模型,即创建一个类,该类Entry将具有名称和分数作为其字段。然后您将获得这些对象的列表。编写一个自定义比较器以按分数降序对它们进行排序。仅此而已 =)

于 2013-03-11T14:43:19.620 回答
0

正如@juvanis 在他的回答中所说,创建一个类来表示每条记录,读取整个文件并将类对象生成到一个列表中,然后对列表进行排序并按排序顺序将对象写入文件中。

这是一个用于表示您的记录的类的示例,它由名称和分数组成。

public class Record {

    private int score;
    private String name;

    public getScore () {
        return score;
    }

    public getName () {
        return name;
    }

    public Record ( String name , int score ) {
        this.name = name;
        this.score = score;
    }

}

为了对您的姓名和分数文件进行排序,请根据分数(我想您想将记录从最高分到最低分进行排序)使用此方法:

public void sortFile () {

    // Reference to the file
    File file = new File ( "sdcard/logger.file" );
    // Check if the file exists
    if ( ! file.exists () ) {
        // File does not exists
        return;
    }
    // Check if the file can be read
    if ( ! file.canRead () ) {
        // Cannot read file
        return;
    }
    BufferedReader bufferedReader = null;
    // The separator between your name and score
    final String SEPARATOR = " ";
    // A list to host all the records from the file
    List < Record > records = new ArrayList < Record > ();

    try {
        bufferedReader = new BufferedReader ( new FileReader ( file ) );
        String line = null;
        // Read the file line by line
        while ( ( line = bufferedReader.readLine () ) != null ) {
            // Skip if the line is empty
            if ( line.isEmpty () )
                continue;
            // Retrieve the separator index in the line
            int separatorIndex = line.lastIndexOf ( SEPARATOR );
            if ( separatorIndex == -1 ) {
                // Separator not found, file is corrupted
                bufferedReader.close ();
                return;
            }
            // Create a record from this line. It is alright if the name contains spaces, because the last space is taking into account
            records.add ( new Record ( line.substring ( 0 , separatorIndex ) , Integer.parseInt ( line.substring ( separatorIndex + 1 , line.length () ) ) ) );
        }
    } catch ( IOException exception ) {
        // Reading error
    } catch ( NumberFormatException exception ) {
        // Corrupted file (score is not a number)
    } finally {
        try {
            if ( bufferedReader != null )
                bufferedReader.close ();
            } catch ( IOException exception ) {
                // Unable to close reader
            }
    }
    bufferedReader = null;

    // Check if there are at least two records ( no need to sort if there are no records or just one)
    if ( records.size () < 2 )
        return;
    // Sort the records
    Collections.sort ( records , new Comparator < Record > () {
            @Override
            public int compare ( Record record1 , Record record2 ) {
            // Sort the records from the highest score to the lowest
                    return record1.getScore () - record2.getScore ();
            }
    } );

    // Replace old file content with the new sorted one
    BufferedWriter bufferedWriter = null;
    try {
        bufferedWriter = new BufferedWriter ( new FileWriter ( file , false ) ); // Do not append, replace content instead
        for ( Record record : records ) {
            bufferedWriter.append ( record.getName () + SEPARATOR + record.getScore () );
            bufferedWriter.newLine ();
        }
        bufferedWriter.flush ();
        bufferedWriter.close ();
    } catch ( IOException exception ) {
        // Writing error
    } finally {
        try {
            if ( bufferedWriter != null )
                bufferedWriter.close ();
        } catch ( IOException exception ) {
            // Unable to close writer
        }
    }
    bufferedWriter = null;

    // You can output the records, here they are displayed in the log
    for ( int i = 0 ; i < records.size () ; i ++ )
        Log.d ( "Record number : " + i , "Name : \"" + records.get ( i ).getName () + "\" , Score : " + records.get ( i ).getScore () );

}

如果有什么你不明白的,请告诉我。如果它按您的预期工作正常,请尝试并让我保持最新状态。

于 2013-03-11T15:33:07.240 回答