JAVA:如何按字母顺序对从文件读取和输出到控制台的字符串进行排序?

时间:2013-03-10 20:07:36

标签: java addressbook contact

我想将按姓氏按字母顺序从文件中读取的联系人排序到控制台?我该怎么做呢?联系人已经从姓氏开始写入文件,我只想在用户想要在控制台中查看联系人时按字母顺序将它们读回应用程序。

// Read from file, print to console. by XXXXX
            // ----------------------------------------------------------
            int counter = 0;
            String line = null;

            // Location of file to read
            File file = new File("contactlist.csv");

            try {

                Scanner scanner = new Scanner(file);

                while (scanner.hasNextLine()) {
                    line = scanner.nextLine();
                    System.out.println(line);
                    counter++;
                }
                scanner.close();
            } catch (FileNotFoundException e) {

            }
            System.out.println("\n" + counter + " contacts in records.");

        }
        break;
        // ----------------------------------------------------------
        // End read file to console. by XXXX

3 个答案:

答案 0 :(得分:2)

在打印之前,将每一行添加到已排序的集合中,作为TreeSet

Set<String> lines = new TreeSet<>();
while (scanner.hasNextLine()) {
    line = scanner.nextLine();
    lines.add(line);
    counter++;
}

for (String fileLine : lines) {
    System.out.println(fileLine);
}

答案 1 :(得分:1)

package main.java.com.example;

import java.io.*;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;

public class ReadFromCSV {
    public static void main(String[] args) {
        try {
            final ClassLoader loader = ReadFromCSV.class.getClassLoader();
            URL url = loader.getResource("csv/contacts.csv");
            if (null != url) {
                File f = new File(url.getPath());
                BufferedReader br = new BufferedReader(new FileReader(f));
                Set<String> set = new TreeSet<String>();
                String str;

                while ((str = br.readLine()) != null) {
                    set.add(str);
                }

                for (String key : set) {
                    System.out.println(key);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 2 :(得分:0)

从文件中读取名称,将它们放在SortedSet类的对象中。