按编号排序文本文件的行,并按降序输出整行

时间:2013-03-11 14:40:27

标签: java android sorting text-files scoring

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

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();
   }

我有办法对每行中的分数和输出名称及其相应分数进行排序吗?谁能帮助我怎么做?谢谢。

2 个答案:

答案 0 :(得分:2)

让一行代表您的数据模型,即创建一个类似Entry的类,其名称和分数将作为其字段。然后你将有一个这些对象的列表。写一个自定义比较器,按照分数的降序对它们进行排序。这就是全部=)

答案 1 :(得分:0)

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

以下是用于表示记录的类的示例,该类包含名称和分数。

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 () );

}

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