【问题标题】:sorting lines of a text file by number present and output the whole lines in descending order按数字对文本文件的行进行排序并按降序输出整行
【发布时间】:2013-02-26 19:01:33
【问题描述】:

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

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

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

【问题讨论】:

    标签: java android sorting text-files scoring


    【解决方案1】:

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

    【讨论】:

    • 你能举个例子让我更好地理解吗?很抱歉,但我是 Java 新手。谢谢@Juvanis
    【解决方案2】:

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

    如果有不明白的地方,请告诉我。 试试看,如果它按您的预期正常工作,让我保持最新状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2021-12-28
      • 2014-02-16
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多