Advertisement
Guest User

Untitled

a guest
Feb 17th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. Scanner scan = new Scanner(System.in);
  2.         //Read file name.
  3.         String filename = scan.nextLine();
  4.        
  5.         //Create output map.
  6.         HashMap<String, Integer> map = new HashMap<>();
  7.         BufferedReader br = null;
  8.         String log;
  9.         try {
  10.             File input = new File(filename);
  11.             br = new BufferedReader(new FileReader(input));
  12.             while ((log = br.readLine()) != null) {
  13.                 String[] data = log.split(" ");
  14.                 map.put(data[0], map.getOrDefault(data[0], 0) + 1);
  15.             }
  16.         }catch(IOException e){
  17.             e.printStackTrace();;
  18.         }finally {
  19.             if(br != null) {
  20.                 try {
  21.                     br.close();
  22.                 } catch (IOException e) {
  23.                     e.printStackTrace();
  24.                 }
  25.             }
  26.         }
  27.  
  28.         File output = new File( "record_" + filename);
  29.         FileWriter writer = null;
  30.         try {
  31.             writer = new FileWriter("record_" + filename);
  32.             for(Map.Entry<String, Integer> entry: map.entrySet()){
  33.                 writer.write(entry.getKey() + " " + entry.getValue() + "\n");
  34.             }
  35.         } catch (IOException e) {
  36.             e.printStackTrace();
  37.         }finally {
  38.             if(writer != null){
  39.                 try {
  40.                     writer.close();
  41.                 } catch (IOException e) {
  42.                     e.printStackTrace();
  43.                 }
  44.  
  45.             }
  46.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement