Java:排序文本文件行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19495642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:45:13  来源:igfitidea点击:

Java: Sorting text file lines

javasortingtext-files

提问by Deoff

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 的事情,但我一生都无法想出一种方法来通过第二个或第三个字段来做到这一点我觉得我错过了一些明显的东西。

采纳答案by Tyler

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 fileonce 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. Once you have your compareTo method you will be able to call Collections.sort(List list) passing your list of Movie.

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

Here are some resources on implementing Comparable.
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
Why should a Java class implement comparable?

这里有一些关于实现 Comparable 的资源。
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
为什么 Java 类要实现可比性?

回答by AppX

What you want to do is to use java.util.Comparatorand Collections.sort. More on this can be found: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

你想要做的是使用java.util.ComparatorCollections.sort。可以找到更多关于此的信息:http: //docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

回答by Andrew Schuster

The String class has a very helpful static method called "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.

String 类有一个非常有用的静态方法,称为“split”。您所做的就是调用 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!

希望您可以使用它并使其适应您的问题。
祝你好运!

回答by Hussain Shabbir

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

回答by AppX

Following @Tyler answer. 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());Here comes an example of both.

按照@Tyler 的回答。您可以在 Movie 类中拥有一个默认实现以及可以通过调用实现的其他排序顺序Collections.sort(movieList, new MyComparator());。这里提供了两者的示例。

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

回答by Prabhakaran Ramaswamy

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..

如果您对此有任何疑问,请告诉我..

回答by diziaq

This solution uses Java 8 APIs.

此解决方案使用 Java 8 API。

You don't really need to have an explicit implementation of Comparatoror create a Comparableclass. Using Comparator.comparingwith lambda we can elegantly sort lines by custom key.

您实际上不需要显式实现Comparator或创建Comparable类。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);
    }
}