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 に答える