如何使用Java对文本文件中的记录进行排序? [英] How do I sort records in a text file using Java?

查看:208
本文介绍了如何使用Java对文本文件中的记录进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

txt文件中数据的一些修改。
我已经尝试了建议的代码,但是我没有成功地使用这种格式在txt文件中写入它。我尝试了collection.sort,但是以长行写入数据。

Some amendment of the data in txt file. I have tried the suggested code but Im not successfully write it again in the txt file with this format.I've tried the collection.sort but it write the data in long line.

我的txt文件包含以下数据:

My txt file contain these data:

Monday
Jessica  Run      20mins
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Tuesday
Mess     Run      20mins
Alba     Walk     20mins
Christy  Jogging  40mins
Bobby    Run      10mins

如何按升序对这些数据进行排序,并在排序后再次存储在txt文件中? p>

How can I sort those data in ascending order and store it again in txt file after sorting?

Monday
Alba     Walk     20mins
Amy      Jogging  40mins
Bobby    Run      10mins
Jessica  Run      20mins
Tuesday
Alba     Walk     20mins
Bobby    Run      10 mins
Christy  Jogging  40mins
Mess     Run      20mins
Jessica  Run      20mins


解决方案

这是我想出的东西:

import java.io.*;
import java.util.*;

public class Sort {

    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader("fileToRead"));
        Map<String, String> map=new TreeMap<String, String>();
        String line="";
        while((line=reader.readLine())!=null){
            map.put(getField(line),line);
        }
        reader.close();
        FileWriter writer = new FileWriter("fileToWrite");
        for(String val : map.values()){
            writer.write(val);  
            writer.write('\n');
        }
        writer.close();
    }

    private static String getField(String line) {
        return line.split(" ")[0];//extract value you want to sort on
    }
}

这篇关于如何使用Java对文本文件中的记录进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆