在Java中对文本文件进行排序

qoefvg9y  于 2023-02-02  发布在  Java
关注(0)|答案(4)|浏览(182)

我有一个文本文件,其中有一个单词列表,我需要使用Java按字母顺序排序。单词位于单独的行上。
我该怎么做呢,把它们读入数组列表然后排序??

a14dhokn

a14dhokn1#

这是一个简单的四步流程,其中三步由Stackoverflow Questions解决:

  1. Read each line and turn them into Java String
    1.将每个Java字符串存储在一个Array中(不认为您需要引用这个字符串)。
  2. Sort your Array
  3. Write out each Java String in your array
dwbf0jvd

dwbf0jvd2#

以下是使用“集合”排序的示例:

public static void sortFile() throws IOException
{     
    FileReader fileReader = new FileReader("C:\\words.txt");
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();

    Collections.sort(lines, Collator.getInstance());

    FileWriter writer = new FileWriter("C:\\wordsnew.txt"); 
    for(String str: lines) {
      writer.write(str + "\r\n");
    }
    writer.close();
}

您也可以像这样使用自己的归类:

Locale lithuanian = new Locale("lt_LT");
Collator lithuanianCollator = Collator.getInstance(lithuanian);
yebdmbv4

yebdmbv43#

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

public class example
{
    TreeSet<String> tree=new TreeSet<String>();
    public static void main(String args[])
    {
        new example().go();
    }
    public void go()

    {
        getlist();
        System.out.println(tree);

    }
     void getlist()
    {
        try
        {
            File myfile= new File("C:/Users/Rajat/Desktop/me.txt");
            BufferedReader reader=new BufferedReader(new FileReader(myfile));
            String line=null;
            while((line=reader.readLine())!=null){
                addnames(line);

            }
        reader.close();
        }

        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
    void addnames(String a)
    {
           tree.add(a);
           for(int i=1;i<=a.length();i++)
           {

           }
    }
}
vc9ivgsu

vc9ivgsu4#

public List<String> readFile(String filePath) throws FileNotFoundException {
    List<String> txtLines = new ArrayList<>();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while (!((line = reader.readLine()) == null)) {
            txtLines.add(line);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return txtLines.stream().sorted().collect(Collectors.toList());
}

相关问题