0

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

// 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
4

3 回答 3

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);
}
于 2013-03-10T20:14:37.980 回答
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();
        }
    }
}
于 2013-03-10T21:32:49.797 回答
0

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

于 2013-03-10T20:14:54.277 回答