Advertisement
Booster

Write Into File Word Occurrences In Text HashMap Sort Desc

Jan 1st, 2015
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.90 KB | None | 0 0
  1. package readWriteFromFile;
  2.  
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.HashMap;
  6. import java.util.LinkedHashMap;
  7. import java.util.LinkedList;
  8. import java.util.List;
  9. import java.util.Map.Entry;
  10. import java.util.Scanner;
  11. import java.io.File;
  12. import java.io.FileNotFoundException;
  13. import java.io.PrintStream;
  14. import java.io.UnsupportedEncodingException;
  15.  
  16. /**
  17.  * create file words.txt read words from file split line to separate words
  18.  * create file text.txt count every wordArr[i] occurrence in text.txt save
  19.  * occurrence to Hashmap sort Hashmap through LinkedList, LinkedHashmap
  20.  * Collection.sort, Comparator create output file result.txt
  21.  *
  22.  * Напишете програма, която прочита списък от думи от файл, наречен words.txt,
  23.  * преброява колко пъти всяка от тези думи се среща в друг файл text.txt и
  24.  * записва резултата в трети файл – result.txt, като преди това ги сортира по
  25.  * брой на срещане в намаляващ ред
  26.  *
  27.  * @author Azbe
  28.  *
  29.  */
  30.  
  31. public class WordsCounterSortWrite {
  32.    
  33.     public static void main(String[] args) {
  34.         File fileWords = new File("src//readWriteFromFile//words.txt");
  35.         File fileText = new File("src//readWriteFromFile//text.txt");
  36.         Scanner fileRead = null;
  37.         Scanner fileRead2 = null;
  38.         PrintStream fileWrite = null;
  39.         try {
  40.             fileRead = new Scanner(fileWords, "windows-1251");
  41.             String[] wordArr = fileRead.nextLine().split("\\s+");
  42.             fileRead2 = new Scanner(fileText, "windows-1251");
  43.             HashMap<String, Integer> wordOccurrence = new HashMap<String, Integer>();
  44.             for (String word : wordArr) {
  45.                 int occurrence = 0;
  46.                 /*
  47.                  * The problem here is that after first reading the file,
  48.                  * Scanner hasNextLine => false and don't enter in the while for
  49.                  * next word. So I close the scanner after every read iteration
  50.                  * of the file and reopen again.
  51.                  */
  52.                 while (fileRead2.hasNextLine()) {
  53.                     String line = fileRead2.nextLine();
  54.                     int result = 0;
  55.                     while (result != -1) {
  56.                         result = line.indexOf(word, result + 1);
  57.                         if (result != -1) {
  58.                             occurrence++;
  59.                         }
  60.                     }
  61.                 }
  62.                 if (fileRead2 != null) {
  63.                     fileRead2.close();
  64.                     fileRead2 = new Scanner(fileText, "windows-1251");
  65.                 }
  66.                 wordOccurrence.put(word, occurrence);
  67.             }
  68.             wordOccurrence = sortByComparator(wordOccurrence);
  69.  
  70.             fileWrite = new PrintStream("src//readWriteFromFile//result.txt",
  71.                     "windows-1251");
  72.             for (Entry<String, Integer> pair : wordOccurrence.entrySet()) {
  73.                 fileWrite.println(pair.getKey() + " --> " + pair.getValue());
  74.                 System.out.println((pair.getKey() + " --> " + pair.getValue()));
  75.             }
  76.         } catch (FileNotFoundException fnf) {
  77.             System.out.println("File not found");
  78.         } catch (UnsupportedEncodingException uee) {
  79.             System.out.println("Unsupported encoding");
  80.         } finally {
  81.             if (fileRead != null) {
  82.                 fileRead.close();
  83.             }
  84.             if (fileRead2 != null) {
  85.                 fileRead2.close();
  86.             }
  87.             if (fileWrite != null) {
  88.                 fileWrite.close();
  89.             }
  90.         }
  91.     }
  92.  
  93.     private static HashMap<String, Integer> sortByComparator(
  94.             HashMap<String, Integer> unsortMap) {
  95.  
  96.         List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(
  97.                 unsortMap.entrySet());
  98.  
  99.         // Sorting the list based on values
  100.         Collections.sort(list, new Comparator<Entry<String, Integer>>() {
  101.             public int compare(Entry<String, Integer> entry1,
  102.                     Entry<String, Integer> entry2) {
  103.  
  104.                 return entry2.getValue().compareTo(entry1.getValue());
  105.  
  106.             }
  107.         });
  108.  
  109.         // Maintaining insertion order with the help of LinkedList
  110.         HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
  111.         for (Entry<String, Integer> entry : list) {
  112.             sortedMap.put(entry.getKey(), entry.getValue());
  113.         }
  114.  
  115.         return sortedMap;
  116.     }
  117.  
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement