пятница, 29 сентября 2017 г.

compare keys and values in properties files java

package com.mycomp;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
        String filename1 = args[0];
        String filename2 = args[1];

        if (filename1 != null && filename2 != null) {

            System.out.println("(A): " + filename1 + " (B):" + filename2);

            try {
                Properties properties1 = new Properties();
                properties1.load(new FileInputStream(filename1));
                Properties properties2 = new Properties();
                properties2.load(new FileInputStream(filename2));

                HashMap<String, String> map1 = getPropsMap(properties1);
                HashMap<String, String> map2 = getPropsMap(properties2);

                HashMap<String, String> all = new HashMap<>();
                all.putAll(map1);
                all.putAll(map2);

                Iterator<String> iterator = all.keySet().iterator();
                while (iterator.hasNext()) {
                    String nextKey = iterator.next();

                    if (!map1.containsKey(nextKey)) {
                        System.out.println("In (A) no key: " + nextKey);
                    }

                    if (!map2.containsKey(nextKey)) {
                        System.out.println("In (B) no key: " + nextKey);
                    }

                    if (map1.containsKey(nextKey) && map2.containsKey(nextKey)) {
                        String val1 = map1.get(nextKey);
                        String val2 = map2.get(nextKey);
                        if (!val2.equals(val1)) {
                            System.out.println("Key " + nextKey + " value in (A):" + val1 + " value in (B):" + val2);
                        }
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static HashMap<String, String> getPropsMap(Properties properties) {
        Set<Map.Entry<Object, Object>> entries1 = properties.entrySet();
        Iterator<Map.Entry<Object, Object>> iterator = entries1.iterator();
        HashMap<String, String> map = new HashMap<>();
        while (iterator.hasNext()) {
            Map.Entry<Object, Object> next = iterator.next();
            map.put(next.getKey().toString(), next.getValue().toString());
        }
        return map;
    }
}