сортировать данные в файле по алфавиту в Java - PullRequest
0 голосов
/ 29 апреля 2020

Вот метод, который я написал, чтобы прочитать данные из файла (symptom.txt) и записать результат в файл (result.out). Теперь я должен отсортировать результат в файле (данные в result.out). Как мне это сделать?

public static void readSymptomDataFromFile() throws IOException {
    // first get input
    BufferedReader reader = new BufferedReader(new FileReader("symptoms.txt"));
    String line = reader.readLine();
    Map<String, Integer> counter = new HashMap<>();

    while (line != null) {
        System.out.println("symptom from file: " + line);
        // we check if the symptom exists in the file and we count its number of
        // occurrences
        if (counter.containsKey(line)) {
            counter.put(line, counter.get(line) + 1);
        } else {
            counter.put(line, 1);
        }

        line = reader.readLine(); // get another symptom
    }
    // close resources
    reader.close();
    // displays the number of occurrences
    counter.forEach((key, value) -> System.out.println(key + ":" + value));
    // Write the symptom list to file "result.out"
    File file = new File("result.out");
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    PrintWriter printWriter = new PrintWriter(fileOutputStream);
    for (Map.Entry<String, Integer> map : counter.entrySet()) {
        printWriter.println(map.getKey() + "=" + map.getValue());
    }
    // close resources
    printWriter.close();
    fileOutputStream.close();

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...