Java:排序文本文件行 [英] Java: Sorting text file lines

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

问题描述

我正在使用eclipse,我正在尝试对大约40行的文本文件进行排序,如下所示:

I'm using eclipse and I'm trying to sort a text file with about 40 lines that look like this:

1,Terminator,1984,Schwarzenegger
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
5,Alien,1979,Weaver

我希望按字母顺序对第二个字段进行排序,以便将文本文件更改为看起来像这个:

I want sort them alphabetically by the second field so that the text file is altered to look like this:

5,Alien,1979,Weaver
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
1,Terminator,1984,Schwarzenegger

我很确定我应该做一些涉及对它们进行标记的事情(我已经做过它来展示它)和一个BufferedWriter但是我不能为我的生活想办法做到这一点在第二或第三场,我觉得我错过了一些明显的东西。

I'm fairly certain I should be doing something involving tokenizing them (which I've already done to display it) and a BufferedWriter but I can't for the life of me think of a way to do it by the second or third field and I feel like I'm missing something obvious.

推荐答案

你首先当然需要读取文件,你可以在这里学习如何做。

Java:如何阅读文本文件

You will first of course need to read a file, which you can learn how to do here.
Java: How to read a text file

这个例子将提供一些方法,一旦你写文件已经对您的数据进行了排序。

如何创建文件并用Java写入?

This example will provide several ways you may write the file once you have sorted your data.
How do I create a file and write to it in Java?

至于排序,我建议创建一个类Movie,它看起来类似于

As for sorting, I recommend creating a class Movie, which would look similar to

public class Movie implements Comparable<Movie> {  
    private String name;
    private String leadActor;
    private Date releaseDate;

    public Movie(String name, String leadActor, String releaseDate) {

    }

    @Override
    public int compareTo(Movie other) {

    }
}  

我留给你填写构造函数和compareTo方法的其余部分。一旦你有了compareTo方法,你就可以通过你的电影列表调用Collections.sort(列表列表)。

Ill leave it to you fill in the rest of the constructor and compareTo method. Once you have your compareTo method you will be able to call Collections.sort(List list) passing your list of Movie.

以下是实现Comparable的一些资源

http:// docs.oracle.com/javase/tutorial/collections/interfaces/order.html

为什么Java类可以实现可比性?

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

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