简体   繁体   English

Java:排序文本文件行

[英]Java: Sorting text file lines

I'm using eclipse and I'm trying to sort a text file with about 40 lines that look like this: 我正在使用eclipse,我正在尝试对大约40行的文本文件进行排序,如下所示:

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

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. 我相当肯定我应该做一些涉及对它们进行标记的事情(我已经做过它来展示它)和一个BufferedWriter但我不能为我的生活想到一种方法来做到第二或第三场我觉得我错过了一些明显的东西。

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? 如何创建文件并用Java写入?

As for sorting, I recommend creating a class Movie, which would look similar to 至于排序,我建议创建一个类似于Movie的类

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) {

    }
}  

Ill leave it to you fill in the rest of the constructor and compareTo method. 我会留给你填写构造函数和compareTo方法的其余部分。 Once you have your compareTo method you will be able to call Collections.sort(List list) passing your list of Movie. 获得compareTo方法后,您将能够通过电影列表调用Collections.sort(列表列表)。

Here are some resources on implementing Comparable . 以下是有关实施Comparable的一些资源。
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
Why should a Java class implement comparable? 为什么Java类可以实现可比性?

Your comparator 你的比较器

class SampleComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
           String array1[] = o1.split(",");
           String array2[] = o2.split(",");
           return array1[1].compareTo(array2[1]);
   }
}

Your Sorting 你的排序

String [] lines= {"1,Terminator,1984,Schwarzenegger",
                       "2,Avatar,2009,Worthington",
                       "3,Avengers,2012,Downey",
                       "4,Starwars,1977,Hammill",
                       "5,Alien,1979,Weaver"};
List<String> rowList = new ArrayList<String>(Arrays.asList(lines));
Collections.sort(rowList, new SampleComparator());
for (String string : rowList) {
     System.out.println(string);
}   

Your Output 你的输出

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

If you have any doubt on this let me know.. 如果您对此有任何疑问,请告诉我..

What you want to do is to use java.util.Comparator and Collections.sort . 你想要做的是使用java.util.ComparatorCollections.sort More on this can be found: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html 有关这方面的更多信息,请访问: http//docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

The String class has a very helpful static method called "split". String类有一个非常有用的静态方法叫做“split”。 All you do is call split and put it in the delimiter and it gives back a String array with the split up string. 你要做的只是调用split并将它放在分隔符中,然后它返回一个带有分割字符串的String数组。

Here's an example: 这是一个例子:

String line = "How,Now,Brown,Cow";
String[] splitLine = line.split(",");
for(String l: splitLine)
{
    System.out.println(l);
}

The above code would print the following: 上面的代码将打印以下内容:

How
Now
Brown
Cow

Hopefully you can use this and adapt it to your problem. 希望您可以使用它并使其适应您的问题。
Good luck! 祝好运!

Following @Tyler answer. 关注@Tyler回答。 You can have a default implementation in the Movie class and additional sort orders that you can implement by calling Collections.sort(movieList, new MyComparator()); 您可以在Movie类中使用默认实现,也可以通过调用Collections.sort(movieList, new MyComparator());实现其他排序顺序Collections.sort(movieList, new MyComparator()); Here comes an example of both. 以下是两者的一个例子。

package com.stackoverflow;


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

    public Movie(String name, String leadActor, String releaseDate) {
        this.name = name;
        this.leadActor = leadActor;
        this.releaseDate = releaseDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLeadActor() {
        return leadActor;
    }

    public void setLeadActor(String leadActor) {
        this.leadActor = leadActor;
    }

    public String getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(String releaseDate) {
        this.releaseDate = releaseDate;
    }

    @Override

    public int compareTo(Movie other) {
        return getName().compareTo(other.getName());
    }
}

And if you want to make your own comparator called on your collection: 如果你想在你的集合上调用你自己的比较器:

package com.stackoverflow;

import java.util.Comparator;

public class MyComparator  implements Comparator<Movie> {


    @Override
    public int compare(Movie o1, Movie o2) {
        return o1.getLeadActor().compareTo(o2.getLeadActor());
    }
}

Try like this :-- 试试这样: -

ArrayList ar=new ArrayList();
String [] arr=new String[10];
int i=0;
try {
    Scanner sc=new Scanner(file);

    while (sc.hasNextLine()) 
    {
        String ss=sc.nextLine();
        i=i+1;
        arr[i]=ss;
    }
    ar.add(arr[5]);
    ar.add(arr[2]);
    ar.add(arr[3]);
    ar.add(arr[4]);
    ar.add(arr[1]);
    System.out.println(ar);
}

This solution uses Java 8 APIs. 此解决方案使用Java 8 API。

You don't really need to have an explicit implementation of Comparator or create a Comparable class. 您实际上不需要具有Comparator的显式实现或创建Comparable类。 Using Comparator.comparing with lambda we can elegantly sort lines by custom key. 使用Comparator.comparing与lambda我们可以通过自定义键优雅地排序行。

import java.io.IOException;
import java.nio.file.*;
import java.util.Comparator;
import java.util.stream.Stream;

public class FileSortWithStreams {

    public static void main(String[] args) throws IOException {
        Path initialFile = Paths.get("files/initial.txt");
        Path sortedFile = Paths.get("files/sorted.txt");

        int sortingKeyIndex = 1;
        String separator = ",";

        Stream<CharSequence> sortedLines =
        Files.lines(initialFile)
             .map(s -> s.split(separator))
             .sorted(Comparator.comparing(s -> s[sortingKeyIndex]))
             .map(s -> String.join(separator, s));

        Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM