Storing a map in a file with the item as key and category as property can be easily done by using java.util.Properties
.
java.util.Properties
is an extension of java.util.Hashtable
which is very similar to java.util.HashMap
.
So you could use code similar to the example below in order to serialize your item - category map into a properties file and to read it back from a file:
Properties properties = new Properties();
properties.setProperty("foo", "cat1");
properties.setProperty("ba", "cat1");
properties.setProperty("fooz", "cat2");
properties.setProperty("baz", "cat2");
File storage = new File("index.properties");
// write to file
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(storage), "UTF-8"))) {
properties.store(writer, "index");
}
// Read from file
Properties readProps = new Properties();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(storage), "UTF-8"))) {
readProps.load(reader);
}
if(!readProps.equals(properties)) {
throw new IllegalStateException("Written and read properties do not match");
}
System.out.println(readProps.getProperty("foo"));
System.out.println(readProps.getProperty("fooz"));
If you run the code it will print out:
cat1
cat2
If you edit the created index.properties file, this is what you see:
#index
#Mon Oct 30 15:41:35 GMT 2017
fooz=cat2
foo=cat1
baz=cat2
ba=cat1