Guest User

Untitled

a guest
Feb 16th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import static java.lang.Thread.sleep;
  7. import java.util.Comparator;
  8. import java.util.LinkedHashMap;
  9. import java.util.Map;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12. import java.util.stream.Collectors;
  13.  
  14. public class Output {
  15.  
  16. public Output(Map<String, Integer> word) {
  17.  
  18. System.out.println("Proccessed URL's now writing to File.........");
  19. String fileName = "CrawledWords.txt";
  20. File file = new File(fileName);
  21. /*if (file.exists()) {
  22. System.out.println("File already exists");
  23. System.exit(0);
  24. }*/
  25.  
  26. // open output stream and printwriter to print to file the formatted
  27. data
  28. FileOutputStream fileOut = null;
  29. try {
  30. fileOut = new FileOutputStream(fileName);
  31. } catch (FileNotFoundException ex) {
  32.  
  33. }
  34. try (PrintWriter printOut = new PrintWriter(fileOut)) {
  35.  
  36. // sorting the method in decending order and limiting it to 50 keys,
  37. modified the code from https://www.mkyong.com/java/how-to-sort-a-map-in-
  38. java/
  39. Map<String, Integer> words = word.entrySet().stream()
  40.  
  41. .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) // sort the
  42. map in decending order by value
  43. .limit(50) // limiting the top 50 values
  44. .collect(Collectors.toMap(Map.Entry::getKey,
  45. Map.Entry::getValue,
  46. (oldValue, newValue) -> oldValue,
  47. LinkedHashMap::new));
  48.  
  49. words.forEach((k, v) -> printOut.println(k + " " + v)); // print Map
  50. keys and values to the file
  51. try {
  52. sleep(1000);
  53. } catch (InterruptedException ex) {
  54. Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null,
  55. ex);
  56. }
  57. printOut.flush(); // flush the printwriter
  58. System.out.println(fileName + " has been created in your working
  59. directory");
  60. }
  61. try {
  62. fileOut.close(); //close the outputstream
  63. } catch (IOException ex) {
  64. Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null,
  65. ex);
  66. }
  67. }
  68. }
Add Comment
Please, Sign In to add comment