Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import static java.lang.Thread.sleep;
- import java.util.Comparator;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import java.util.stream.Collectors;
- public class Output {
- public Output(Map<String, Integer> word) {
- System.out.println("Proccessed URL's now writing to File.........");
- String fileName = "CrawledWords.txt";
- File file = new File(fileName);
- /*if (file.exists()) {
- System.out.println("File already exists");
- System.exit(0);
- }*/
- // open output stream and printwriter to print to file the formatted
- data
- FileOutputStream fileOut = null;
- try {
- fileOut = new FileOutputStream(fileName);
- } catch (FileNotFoundException ex) {
- }
- try (PrintWriter printOut = new PrintWriter(fileOut)) {
- // sorting the method in decending order and limiting it to 50 keys,
- modified the code from https://www.mkyong.com/java/how-to-sort-a-map-in-
- java/
- Map<String, Integer> words = word.entrySet().stream()
- .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) // sort the
- map in decending order by value
- .limit(50) // limiting the top 50 values
- .collect(Collectors.toMap(Map.Entry::getKey,
- Map.Entry::getValue,
- (oldValue, newValue) -> oldValue,
- LinkedHashMap::new));
- words.forEach((k, v) -> printOut.println(k + " " + v)); // print Map
- keys and values to the file
- try {
- sleep(1000);
- } catch (InterruptedException ex) {
- Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null,
- ex);
- }
- printOut.flush(); // flush the printwriter
- System.out.println(fileName + " has been created in your working
- directory");
- }
- try {
- fileOut.close(); //close the outputstream
- } catch (IOException ex) {
- Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null,
- ex);
- }
- }
- }
Add Comment
Please, Sign In to add comment