Advertisement
cd62131

FIle Read And Write

Dec 18th, 2013
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.43 KB | None | 0 0
  1. import java.io.BufferedWriter;
  2. import java.nio.charset.Charset;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. import java.nio.file.StandardOpenOption;
  6. import java.util.Map;
  7. import java.util.Map.Entry;
  8. import java.util.Scanner;
  9. import java.util.TreeMap;
  10.  
  11. public class MapExample {
  12.   public static void main(String[] args) {
  13.     Scanner reader = null;
  14.     try {
  15.       reader = new Scanner(Paths.get("C:\\List1.txt"));
  16.     }
  17.     catch (Exception e) {
  18.     }
  19.     BufferedWriter writer = null;
  20.     try {
  21.       writer =
  22.         Files.newBufferedWriter(Paths.get("C:\\List2.txt"),
  23.           Charset.forName("UTF-8"), StandardOpenOption.WRITE);
  24.     }
  25.     catch (Exception e) {
  26.     }
  27.     if (reader == null || writer == null) System.exit(1);
  28.     Map<String, Integer> map = new TreeMap<String, Integer>();
  29.     while (reader.hasNextLine()) {
  30.       String name = reader.nextLine().trim();
  31.       if (map.get(name) == null) map.put(name, 0);
  32.       else map.put(name, map.get(name) + 1);
  33.     }
  34.     reader.close();
  35.     while (!map.isEmpty()) {
  36.       Entry<String, Integer> max = map.entrySet().iterator().next();
  37.       for (Entry<String, Integer> e: map.entrySet())
  38.         if (max.getValue() < e.getValue()) max = e;
  39.       try {
  40.         writer.write(max.getKey() + "\n");
  41.       }
  42.       catch (Exception e) {
  43.       }
  44.       map.remove(max);
  45.     }
  46.     try {
  47.       writer.close();
  48.     }
  49.     catch (Exception e) {
  50.     }
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement