JAVA在新文件中按升序对行进行排序并显示它

时间:2014-03-20 18:30:27

标签: java eclipse sorting printwriter

我正在使用eclipse在java中编写一个简单的游戏猜测。现在我想按升序打印出细节。我在这个论坛上尝试了很多方法,但无法解决。这就是我需要你帮助的原因。

我的代码如下:

File f = new File ("scores.txt");
    // name of the folder created at the root of the project
    String ligne;
    try
    {
    PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter (f, true)));
    if (numberOfTries==1){
        pw.println (numberOfTries + " try by " + str )  ; 
    }
    else if (numberOfTries!=1){
        pw.println (numberOfTries + " tries by " + str )    ; 
    }

//  pw.println (numberOfTries)  ;
    pw.close ();    
    // this line MUST be written.
    }

    catch (IOException exception) {
    System.out.println ("Error while writing data:" + exception.getMessage());
    }       

    BufferedReader ficTexte;
    // to read from a folder text.
try {
        ficTexte = new BufferedReader (new FileReader(f));
        do {
            ligne= ficTexte.readLine();
            if (ligne !=null)
            // if the line is not empty.
               System.out.println(ligne);
        } while (ligne !=null);
        ficTexte.close();
        System.out.println("\n");
        }
    // Show message in case of errors.
        catch (FileNotFoundException e) {
            System.out.println (e.getMessage());
        } 
        catch (IOException e) {
            System.out.println (e.getMessage());
        }

}

假设我有

3 tries by Vibe
2 tries by NoNo
10 tries by Caroline
7 tries by Mata
10 tries by Lionel

我希望它安排如下:

2 tries by NoNo
3 tries by Vibe
7 tries by Mata
10 tries by Caroline
10 tries by Lionel

怎么可能呢?

2 个答案:

答案 0 :(得分:0)

试试这个:

private static final Comparator<String> CMP = new Comparator<String>()
{
    @Override
    public int compare(final String a, final String b)
    {
        final int inta = Integer.parseInt(a.split("\\s+")[0]);
        final int intb = Integer.parseInt(b.split("\\s+")[0]);
        return Integer.compare(inta, intb);
    }
}

然后,在代码后面:

final Path file = Paths.get("scores.txt");
final List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
Collections.sort(lines, CMP);

for (final String line: lines)
    System.out.println(line);

(类似地,您应该使用Files.newBufferedWriter()为您的文件获取Writer

答案 1 :(得分:0)

基本解决方案:

  1. 编写代码以读取文件中的所有行并将它们存储在您选择的List中(ArrayList似乎合理)。查看Scanner
  2. 编写自定义比较器以执行排序。查看Comparator。如在fge答案中,比较两个字符串。与答案不同的是,不要使用匹配器,这对我来说太过分了。而是只调用String.split()并引用返回数组中的第一个元素(索引零)。将此转换为数字执行比较。
  3. Collections.sort(rows,yourComparator)(就像在fge答案中一样)。
  4. 将行写入您选择的文件。